Ethan Webster
Ethan Webster

Reputation: 749

PDO Fetch Array like MySQLi

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?

Upvotes: 0

Views: 18762

Answers (1)

gen_Eric
gen_Eric

Reputation: 227280

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);

Upvotes: 6

Related Questions