Py学习  »  DATABASE

通过数组循环并将值传递给mysql query php

kanishka • 4 年前 • 773 次点击  

我有以下JSON对象

[
  {
    "var1": "ID001",
    "var2": "ROY",
    "var3": "16"
  },
  {
    "var1": "ID002",
    "var2": "MARK",
    "var3": "15"
  },
  {
    "var1": "ID003",
    "var2": "PETER",
    "var3": "15"
  }
]

我想循环访问JSON,并向下面的MySQL查询传递一个值

$select_data=mysqli_query($connsow, "select * from salary where col1 = '$var1' and col2 = '$var2'");

下面是我的代码,我使用了foreach循环,但它总是选择JSON对象中的第一个值。我无法循环整个JSON并将值传递给查询

foreach($rows as $item) { 
    $cust_ord_no = $item['var1'];
    $cont_n = $item['var2'];
    $select_data=mysqli_query($connsow, "select * from test where col1 = '$var1' and col2 = '$var2'");
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38947
 
773 次点击  
文章 [ 2 ]  |  最新文章 4 年前
Gajanan Kolpuke
Reply   •   1 楼
Gajanan Kolpuke    5 年前

您正试图访问名为的键,而不是该键,您必须使用在SQL之前定义的变量。

$rows = json_decode($strJSON, true);

$select_data = [];
foreach( $rows  as $item ) {
    $cust_ord_no = $item['var1'];
    $cont_n = $item['var2'];
    $strSQL = "select * from test where col1 = '$cust_ord_no' and col2 = '$cont_n'";
    $select_data[] =mysqli_query($connsow, $strSQL);
}
Madhur Bhaiya
Reply   •   2 楼
Madhur Bhaiya    5 年前
  • 首先将JSON转换为数组usng json_decode 第二个参数设置为的函数 true 。然后,可以循环遍历数组。

执行以下操作:

$rows = json_decode($rows, true);