如何迭代mysqli_fetch_array()的结果?

时间:2012-08-19 13:50:00

标签: php mysqli

在以下代码中,结果包含多个产品,每个产品都有几列:

$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";
}

但输出只迭代单个产品的每一列:

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

如何获得$array[0]['MSRP']评估95.7

的二维数组

3 个答案:

答案 0 :(得分:3)

$ary = $result->fetch_array(MYSQLI_ASSOC)一次只能获得一条记录,这是您案例中的第一条记录,您需要使用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";
    }

}

答案 1 :(得分:1)

我相信这会奏效:

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

这意味着虽然有更多记录,但它会继续并将它们放入数组并打印出来...... 这是基于旧的mysql_fetch_assoc()和mysql_fetch_array()。

祝你好运。

如果你想达到你想要的,你只需要做以下事情:

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

现在$array拥有整个结果集,因此$array[0]['MSRP'] - 将返回您想要的值。

答案 2 :(得分:1)

您需要迭代mysql_fetch命令,而不是该命令的结果。

例如:

$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'];
}