I'm trying to run a simple query with PDO in PHP. The code is pretty simple:
try {
$sql_query = "select * from Articles where title=':article'";
$dbh = get_PDO_connection();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare($sql_query);
$stmt->execute( array( ':article' => "MD Example") );
var_dump($stmt);
$row = $stmt->fetch();
//if($row==null)return 'null';
var_dump($row);
} catch (PDOException $e) {
print $e->getMessage ();
}
var_dump($stmt) always prints:
object(PDOStatement)#3 (1) { ["queryString"]=> string(45) "select * from Articles where title=':article'" }
... no matter what I put into execute(), with no exceptions thrown. And, as the title states, fetch() always returns false. You should know that if I "hard-code" the SQL query into the string, all of this works fine. In other words, if I set $sql_query to "select * from Articles where title='MD Example'", then fetch() returns the expected results. What's going on here?
Remove the quotes from around the placeholder:
$sql_query = "select * from Articles where title=:article";
//---------------------------------------------^^^^^^^^^^^
By using a placeholder, you relinquish responsibility for having to correctly quote strings or not quote numeric values. That becomes the business of PDO to correctly escape and quote the inputs for you.
By leaving in the quotes, rather than use the placeholder, PDO will literally be querying for the value :article in the title column, rather than the value you pass to the execute() array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With