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 } } 
3
  • its not $row->id but its $row['id'] Commented Jun 6, 2013 at 13:44
  • Do not use deprecated mysql_* functions. Commented Jun 6, 2013 at 13:45
  • 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 []. Commented Jun 6, 2013 at 13:46

3 Answers 3

6
foreach($result_list as $row) {

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

Try this.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.