Home > Backend Development > PHP Tutorial > How Can I Achieve Similar Functionality to MySQL's `mysql_fetch_array` Using PDO in PHP?

How Can I Achieve Similar Functionality to MySQL's `mysql_fetch_array` Using PDO in PHP?

DDD
Release: 2024-12-15 03:52:09
Original
379 people have browsed it

How Can I Achieve Similar Functionality to MySQL's `mysql_fetch_array` Using PDO in PHP?

Using PDO to Fetch Results Arrays in PHP

In a quest to mitigate SQL injection vulnerabilities, you are seeking to use PDO instead of regular MySQL connections. Wondering if your PDO script will offer similar functionality to your previous MySQL script, you present a dilemma.

Original Scripts:

PDO Script:

$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);
Copy after login

Regular MySQL Script:

$dbhost = @mysql_connect($host, $user, $pass) or die('Unable to connect to server');

@mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);

$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";

if(!isset($query)){
    echo 'Your search was invalid';
    exit;
} //line 18

$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);
Copy after login

PDO Fetching Functionality

To achieve similar functionality to the while loop you used with your regular MySQL script, you can utilize the PDOStatement.fetchAll method. Here's how:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
Copy after login

Result Array:

This will return an array of associative arrays, with each sub-array containing a row from the result set. For instance, the following code sample would produce the following output:

print_r($result);
Copy after login

Output:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)
Copy after login

This array structure allows you to access the data from each row conveniently, ensuring comparable functionality to your previous MySQL script.

The above is the detailed content of How Can I Achieve Similar Functionality to MySQL's `mysql_fetch_array` Using PDO in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template