CodeMoose
CodeMoose

Reputation: 3025

PDO fetchAll seems to fail when result has single row?

I'm stumped. Consider the following test table:

----------------
| art_projects |
----------------------------------
| project_name | project_creator |
|--------------|-----------------|
| Flying Feet  | 1               |
| Dinosaurs    | 2               |
| Roadblock    | 1               |
----------------------------------

Paired with it, consider the following code (where $db is a confirmed-functional PDO instance):

$dbObj = $db->prepare("SELECT * FROM art_projects WHERE project_creator = ?");
$dbObj->execute([1]);
print_r($dbObj->fetchAll(PDO::FETCH_ASSOC));

Very simple, very little can go wrong. This functions as expected and returns the following result set:

----------------------------------
| project_name | project_creator |
|--------------|-----------------|
| Flying Feet  | 1               |
| Roadblock    | 1               |
----------------------------------

Here's where the problem starts. If I change the execute() to search for ID 2 instead of 1, I'd expect it would return a single-row result for Dinosaurs. It doesn't - I get this instead:

1

When I change $dbObj->fetchAll(...) to $dbObj->fetch(...), though, I get the expected single-row result. The heck...?


Now, I'm pretty new to PDO, but I'm assuming this is expected behavior; I can't seem to find anything about this being an "error", here or elsewhere on Google. Can someone explain this behavior to me?

Furthermore, is there an accepted/effective method to deal with this? IMHO, It's kind of a Catch-22 to test the length of the result set for the sake of using the right fetch method, and it's unreasonable to magically know when your result set is going to be single-row or multiple-row.

Upvotes: 1

Views: 572

Answers (1)

O. Jones
O. Jones

Reputation: 108676

FETCH_ASSOC isn't a valid documented mode for PDO::FetchAll(). When it gets more than one result set row it's probably doing some sort of filling in of an associative array that wipes out the contents.

If I were you I'd loop and do the ordinary fetch() call once per row.

Upvotes: 1

Related Questions