1

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 } } 
Brent
  • 2,385
  • 10
  • 39
  • 63

3 Answers3

6
foreach($result_list as $row) {

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

Try this.

som
  • 4,650
  • 2
  • 21
  • 36
1

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87
1

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
GGio
  • 7,563
  • 11
  • 44
  • 81