0

I know how to fetch a PDO array, but how do I collect data from it like you do with MySQLi's fetch_array?

For example,

MySQLi

$query = $mysqli->query("SELECT * FROM `foo` WHERE `ID`='1'");
$array = $query->fetch_array();

Getting a result

echo $array['bar'];

How would you do this with PDO? I understand you can do this:

PDO

$query = $pdo->prepare("SELECT * FROM `foo` WHERE `ID`='1'");
$query->execute();
$result = $query->fetchAll();

Getting the result

echo $result['bar'];

Does not return the same as MySQLi did

Am I doing something wrong, and is there a way of doing this?

5
  • 4
    Read fetch_style parameter php.net/manual/en/pdostatement.fetch.php PDO::FETCH_ASSOC returns an array indexed by column name as returned in your result set Commented Apr 14, 2014 at 19:52
  • You have to understand, that while the fetch_array() iterates over the whole result set and returns one row at a time, fetchAll() returns the whole result set. Do this instead: $query->fetch(PDO::FETCH_ASSOC) Commented Apr 14, 2014 at 19:54
  • Something I remember from my PHP days that you may find useful is using print_r() and/or var_dump() to divine the often poorly-documented data structures PHP throws at you. Commented Apr 14, 2014 at 19:57
  • @tgies: Nothing is poorly-documented here. The first commenter's link points to a correct documentation. Commented Apr 14, 2014 at 19:58
  • @mark.sagikazar Not in this case, no. Commented Apr 14, 2014 at 20:00

1 Answer 1

6

fetchAll() is not the same as fetch_array().

You want fetch() to get one row, not fetchAll() which gets ALL rows.

$result = $query->fetch(PDO::FETCH_ASSOC);
Sign up to request clarification or add additional context in comments.

7 Comments

Ah, I see now. I'm new to PDO as I want to ditch MySQL and MySQLi all together, as you can probably see. Thank you very much.
+1 I'll add that you should be able to omit the PDO::FETCH_ASSOC because the default is to return an array that is indexed both associatively and numerically.
Is the PDO:: before the FETCH_* absolutely necessary? And why? I believe in MySQLi you just need to parse in FETCH_*
PDO is the class name, and the FETCH_* thing is a constant.
:: means static access. You use -> (eg. $query->). That is object-context. Constants can be accessed statically in a class.
|

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.