Reputation: 7922
I'm having some trouble understanding how to use prepared statements, when you need to match one value against several columns at once.
In other words what instead of doing this:
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
$stmt->bindParam(1, $name);
I wanted to do this:
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where firstname = ? or lastname = ?");
with both '?' representing the same string.
Upvotes: 4
Views: 13448
Reputation: 23
While all of the above answers do work, they won't work with so called "true prepared statements". You will get an error that says "Parameter was not defined" or something similar.
What you need to do then is to just specify two different named parameters and bind the same value.
For example:
$stmt = $db->prepare(
"SELECT * FROM registry WHERE firstname = :firstname OR lastname = :lastname"
);
$stmt->execute(array(":firstname" => $name, ":lastname" => $name));
You can enable true prepared statements the following way:
$options = [ PDO::ATTR_EMULATE_PREPARES => false ];
$pdo = new PDO($dsn, "username", "password", $options);
Upvotes: 1
Reputation: 799
Try...
$stmt = $dbh->prepare("SELECT * FROM registry WHERE firstname = :name OR lastname = :name;");
$stmt->bindParam(':name', $name);
Upvotes: 8
Reputation: 25263
Why not just use a named parameter:
$stmt = $dbh->prepare("SELECT * FROM REGISTRY WHERE firstname = :name OR lastname = :name");
$stmt->bindParam(':name', $name);
Upvotes: 1