Sometimes, we want to use PDO to fetch a results array in PHP.
In this article, we’ll look at how to use PDO to fetch a results array in PHP.
How to use PDO to fetch a results array in PHP?
To use PDO to fetch a results array in PHP, we can use the fetchAll
method.
For instance, we write
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);
to create a prepared statement with prepare
called with a SQL string.
Then we call execute
to run the statement.
Then we call fetchAll
to fetch all the results.
And we fetch them as an associative array by calling it with \PDO::FETCH_ASSOC
.
Conclusion
To use PDO to fetch a results array in PHP, we can use the fetchAll
method.