1

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

$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

4

3 回答 3

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

}
于 2012-08-19T13:55:56.107 回答
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']- 将返回您想要的值。

于 2012-08-19T13:56:14.480 回答
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'];
}
于 2012-08-19T13:58:43.130 回答