1

What does PDO::query actually do ?
Does it query the SQL ?
If it queries the SQL, I think the data must be in the PDOStatement object as the result of the query..
But, what I find is just the SQL statement itself. So, I think it does nothing but just store the sql statement to the PDO statement property.

object(PDOStatement)[2]
public 'queryString' => string 'SELECT * from posts' (length=19)

And, to get the data, we must fetch it using PDOStatement::fetch
So, what does PDO::query do ?
Why doesn't it just get the data ?
Is there any principle of design that makes PDO like this ?

2
Contributors
1
Reply
18
Views
2 Years
Discussion Span
Last Post by cereal
2

Hi,

you actually get the result, just loop it:

$result = $pdo->query("SELECT * FROM posts");

foreach ($result as $key => $value)
    echo $value['title'];

echo 'Total: '. $result->rowCount();

It's not visible through print_r() because the statement is an iterable object, if you want the full array use fetchAll():

print_r($result->fetchAll());

As second parameter you can define the fetch mode, for example:

$result = $pdo->query("SELECT * FROM posts", PDO::FETCH_ASSOC);

For more information check the PDOStatement class:

Also, read the following article, at the end there is a paragraph dedicated to PDO::FETCH_CLASS method, which explains a bit how flexible can be a PDO statement:

Edited by cereal

Votes + Comments
Thanks for your nice answer
nice detailed explainations
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.