Home >Database >Mysql Tutorial >How Can I Fetch a Result Array Using PDO in PHP?
Using PDO to Fetch a Results Array in PHP
You're transitioning your script to utilize PDO for enhanced security against SQL injection attacks. To obtain the same functionality as your regular MySQL script, you need to fetch a result array using PDO.
In your original script, you would have used mysql_fetch_array to retrieve the data as an array. With PDO, you have two options:
A code sample from the PHP documentation:
$sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
This will return an array of associative arrays, with the column names as keys.
Example:
while ($row = $sth->fetch(\PDO::FETCH_ASSOC)) { // Process the current row data }
By utilizing either of these techniques, you can achieve the same functionality as your regular MySQL mysql_fetch_array call and securely fetch a result array using PDO.
The above is the detailed content of How Can I Fetch a Result Array Using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!