Reputation: 2485
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 } }
Upvotes: 1
Views: 32669
Reputation: 26451
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.
Upvotes: 1
Reputation: 7653
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
Upvotes: 1
Reputation: 4656
foreach($result_list as $row) {
$productitems[] = array(
'id' => $row['id'],
'product' => $row['product'],
'price' => $row['price']
);
}
Try this.
Upvotes: 6