Home >Backend Development >PHP Tutorial >How Can I Fetch All Database Results as an Array Using PDO in PHP?
PDO Fetching Results Array in PHP
Problem:
How can programmers leverage PDO to obtain an array of database results, similar to the functionality provided by mysql_fetch_array() in a traditional MySQL connection?
Answer:
Utilizing the PDOStatement.fetchAll method empowers developers with the ability to retrieve an array of results. Alternatively, an iterator pattern with the fetch method can also be employed.
Code Sample for fetchAll:
$sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); /* Fetch all of the remaining rows in the result set */ print("Fetch all of the remaining rows in the result set:\n"); $result = $sth->fetchAll(\PDO::FETCH_ASSOC); print_r($result);
Sample Results:
Array ( [0] => Array ( [NAME] => pear [COLOUR] => green ) [1] => Array ( [NAME] => watermelon [COLOUR] => pink ) )
The above is the detailed content of How Can I Fetch All Database Results as an Array Using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!