Skip to content
Home » MySQL » How to Get PDO Query Result in PHP

How to Get PDO Query Result in PHP

The first method is to use the simple query() of PHP Data Objects (PDO) to return a statement object, and then fetch the statement object to get the result.

...
$sql = "select * from users where username='Foo Bar');
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $user, $pass, $options);
$statement = $dbh -> query($sql);
$result =  $statement -> fetchAll();
var_dump($result);
...

The advantages of this method is simple and easy to understand.

The second method is to prepare() the SQL statement first, then execute and fetch. It's very useful when several conditions are indeterminable at develop-time.

...
$sql = "select * from users where username=?";
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $user, $pass, $options);
$statement = $dbh -> prepare($sql);

$username = "Foo Bar";
$statement -> execute(array($username));
$result =  $statement -> fetchAll();
var_dump($result);
...

You can tell this method is more complicated, but the way to prepare statement in advance is more flexible than the first one. It can execute all kinds of statement, bind values into parameters and escape special characters automatically. It looks like an enhanced version of the first method.

Leave a Reply

Your email address will not be published. Required fields are marked *