Home >Backend Development >PHP Tutorial >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);
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);
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);
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);
Output:
Array ( [0] => Array ( [NAME] => pear [COLOUR] => green ) [1] => Array ( [NAME] => watermelon [COLOUR] => pink ) )
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!