Home >Database >Mysql Tutorial >How Can I Fetch a Result Array Using PDO in PHP?

How Can I Fetch a Result Array Using PDO in PHP?

DDD
DDDOriginal
2024-12-17 04:32:24538browse

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:

  1. PDOStatement.fetchAll method: This method retrieves all rows from the result set and returns them as an array.

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.

  1. PDOStatement.fetch method in an iterator pattern: This method allows you to loop through the result set row-by-row, accessing the data as an array.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn