Mysql Fetch Array Foreach

Mysql Fetch Array Foreach

问题描述:

I am trying to use a foreach loop to set value to populate a table, for some reason my array is showing null inside values. But when I var dump the $result_list[] it shows the array of products, Am i doing this wrong? Thanks

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

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

  $ 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}} 
  code>  pre> 
  div>

foreach($result_list as $row) {

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

Try this.

Change it to,

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

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

to answer your question you are getting back row as an array and not object but yet you still try to access it as an object $row->id. Instead use $row['id'], $row['product'], $row['price'].

Do not use mysql_* functions instead use PDO or MySQLi, for example look how simple it is with PDO:

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