How do iterate the result of mysqli_fetch_array()?

2019-08-07 10:49发布

问题:

in the following code, the result contain several product and each have several column:

$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);
$ary = $result->fetch_array(MYSQLI_ASSOC);
foreach($ary as $key => $element){
  echo "key is $key, element is $element \n";
}

But the output only iterate each column of single product:

key is id, element is 1
key is productCode, element is S10_1678
key is productName, element is 1969 Harley Davidson Ultimate Chopper
key is productLineId, element is 5
key is productScale, element is 1:10
key is productVendor, element is Min Lin Diecast
key is productDescription, element is This replica features working kickstand, front suspension, gear-shift lever, footbrake lever, drive chain, wheels and steering. All parts are particularly delicate due to their precise scale and require special care and attention.
key is quantityInStock, element is 7933
key is buyPrice, element is 48.81
key is MSRP, element is 95.7

how can I get the 2-dimensional array that $array[0]['MSRP'] evaluate 95.7

回答1:

I believe this will work:

while ($ary = $result->fetch_array(MYSQL_ASSOC){
  foreach($ary as $key => $element){
    echo "key is $key, element is $element \n";
  }
}

This means that while there are more records, it'll go ahead and put them in the array and print them... This is based on the old mysql_fetch_assoc() and mysql_fetch_array().

Good luck.

if you want to achieve what you wanted, you'll simply need to do the following:

 while ($ary = $result->fetch_array(MYSQL_ASSOC){
      foreach($ary){
        $array[] = $ary;
      }
    }

now $array has the entire result set, and thus $array[0]['MSRP'] - will return the value you desire.



回答2:

$ary = $result->fetch_array(MYSQLI_ASSOC) only gets one record at a time which was the first record in your case, You will need to use a while

while($ary = $result->fetch_array(MYSQLI_ASSOC)) //fetching one record at a time until end of record
{

    foreach($ary as $key => $element){
      echo "key is $key, element is $element \n";
    }

}


回答3:

You need to iterate the mysql_fetch command,not the results of that command.

Eg example:

$db = connect_db();
$sql = "SELECT * FROM Products";
$result = $db->query($sql);

while($entry = mysql_fetch_assoc($result))
{
  // $entry is an array you with the data of this DB-entry, eg
  echo $entry['MSRP'];
}


标签: php mysqli