简体   繁体   中英

Loop through array and pass value to mysql query php

I have the following JSON object

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

I want to loop through the JSON and pass a value to following MySQL query

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

Below is my code, I used a foreach loop but it always selects the first value in the JSON object. I can't loop through entire JSON and pass the value to query

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'");
}
  • First convert the JSON to array usng json_decode function with second parameter set to true . Then, you can loop through the array.

Do the following:

$rows = json_decode($rows, true);

you are trying to access key with name, instead of that, you have to use a variable which you have defined just before 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM