Woodstock
Woodstock

Reputation: 22926

mysql_fetch_array, seemingly not returning value

I have a result from an SQL query in $result,

$result = $query->fetchall((PDO::FETCH_ASSOC));

It looks like this on a var dump:

  array(7) {
    ["index"]=>
    string(2) "59"
    ["user_id"]=>
    string(32) "154FA6BFDFAA3B283452E84DCC41AF1D"
    ["trigger_price"]=>
    string(2) "33"
    ["currency"]=>
    string(1) "$"
    ["direction"]=>
    string(1) ">"
    ["title"]=>
    string(1) "T"
    ["date_set"]=>
    string(19) "2013-10-09 07:21:17"
  }

When I then try to loop through to access an element of the result set nothing is printed. I'm using this code:

while ($row = mysql_fetch_array($result) )
{
    echo $row["title"];
}

I'm finding so many stumbling blocks in PHP it's driving me insane, it's like there is 10 ways to do everything, but only one of them seems to ever work!!

I'm using MAMP so maybe the syntax is slightly different, correct answer to anyone who can help.

I also tried:

    while ($row = mysql_fetch_array($result, MYSQL_NUM))

and:

while ($row = mysql_fetch_row($result)){
    echo $row;
}

Upvotes: 0

Views: 277

Answers (1)

MrCode
MrCode

Reputation: 64526

After using PDOStatement::fetchAll() you can iterate over the array using a simple foreach:

foreach($result as $row)
{
    echo $row["title"];
}

Alternatively, instead of using PDOStatement::fetchAll() you can use PDOStatement::fetch(), which is roughly the equivalent of mysql_fetch_array():

while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    echo $row["title"];
}

The mysql_* functions cannot be interchanged with PDO and they are deprecated and discouraged.

Upvotes: 2

Related Questions