A Quick Note on Migrating to PDO

Migrating from mySQLi to PDO was really painless. I changed the database access as described previously. Then using the same query as previously, I added the database name `website` and then used the following code:


$qry = "SELECT * FROM product;
$res= $dbWG->query($qry);

if (!$res)
    die(mysqli_error($dbWG));

$numRows = mysqli_num_rows($res);

for ($i = 0; $i < $numRows; $i++) {
    $row   = $res->fetch_array();


$qry = "SELECT * FROM `website`.`product`;
$stmt = $dbWG->prepare($qry);
$stmt->execute();

$results = $stmt->fetchAll();
foreach($results as $row) {

One of the reasons to use PDO is that it has prepared statements that will automatically escape inputs so that injection attacks are mitigated.

It is simple to change the your code if you are using input from the user to construct the query.
If you do a simple convert, like above, to you end up with something like this:


// get the current category name
$qry  = "SELECT name FROM `website`.`book_category` ";
$qry .= "WHERE id = $categoryID";
  
$stmt = $dbWG->prepare($qry);
$stmt->execute();

$results = $stmt->fetch();
categoryName = $results['name'];

A simple change in the query and a bind statement lets PHP automatically escape the user input.


// get the current category name
$qry  = "SELECT name FROM `website`.`book_category` ";
$qry .= "WHERE id = :categoryID";

$stmt = $dbWG->prepare($qry);
$stmt->bindParam(':categoryID', $categoryID);
$stmt->execute();

$results = $stmt->fetch();
$categoryName = $results['name'];

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.