Mysql Fetch Array Foreach

时间:2013-06-06 13:43:34

标签: php mysql arrays

我正在尝试使用foreach循环设置值来填充表,由于某种原因,我的数组在值内显示null。但是当我转储$ result_list []时它会显示产品数组,我这样做错了吗?感谢

$result = mysql_query("SELECT id, product, price FROM products");


$result_list = array();
while($row = mysql_fetch_array($result)) {
   $result_list[] = $row;
}

foreach($result_list as $row) {

    $productitems[] = array(
        'id' => $row->id,
        'product'  => $row->product,
        'price'  => $row->price
    );              
}

var_dump($productitems);


array(2) { [0]=> array(3) { ["id"]=> NULL ["product"]=> NULL ["price"]=> NULL } [1]=> array(3) { ["id"]=> NULL ["product"]=> NULL ["price"]=> NULL } } 

3 个答案:

答案 0 :(得分:6)

foreach($result_list as $row) {

    $productitems[] = array(
        'id' => $row['id'],
        'product'  => $row['product'],
        'price'  => $row['price']
    );              
}

试试这个。

答案 1 :(得分:1)

将其更改为,

foreach($result_list as $row) {
    $productitems[] = array(
       'id' => $row['id'],
       'product'  => $row['product'],
       'price'  => $row['price']
    );
}

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 2 :(得分:1)

回答你的问题,你将行作为一个数组而不是对象,但你仍然试图以对象$row->id的形式访问它。而是使用$row['id']$row['product']$row['price']

不要使用mysql_ *函数而是使用PDO或MySQLi,例如看看PDO有多简单:

$productitems = $pdo->fetchAll(\PDO::FETCH_ASSOC); and then use foreach