Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 } } 
share|improve this question
 
its not $row->id but its $row['id'] –  GGio Jun 6 at 13:44
 
Do not use deprecated mysql_* functions. –  Voitcus Jun 6 at 13:45
 
What is deprecated? –  Brent French Jun 6 at 13:46
 
The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead. Anyway. you need foreach($result_list[] as $row. you forgot the []. –  Kees Sonnema Jun 6 at 13:46

3 Answers

up vote 1 down vote accepted
foreach($result_list as $row) {

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

Try this.

share|improve this answer
 
Thanks it worked :) –  Brent French Jun 6 at 13:47

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.

share|improve this answer
1  
Thanks this worked to, will read into the deprecated functions thanks :D –  Brent French Jun 6 at 13:48
 
Yeah you should. Glad to help you :) –  Rikesh Jun 6 at 13:48

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
share|improve this answer
 
will look into this, thanks for reply –  Brent French Jun 6 at 13:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.