A note on PDO prepared statements

It wasn’t obvious to me that you need to have a different bindParameter statement each time you use a variable in the query. This won’t work.


// query for title information
$qry  = "SELECT * ";
$qry .= "FROM `website_database`.`product`, `website_database`.`product_instance` ";
$qry .= "WHERE product.id = :productID ";
$qry .= "AND product_instance.product_id = :productID";

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

MySql doesn’t look for every instance of :productID in the query and substitute $productID. This is how you do it:


// query for title information
$qry  = "SELECT * ";
$qry .= "FROM `website_database`.`product`, `website_database`.`product_instance` ";
$qry .= "WHERE product.id = :productID1 ";
$qry .= "AND product_instance.product_id = :productID2";

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

Leave a Reply

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