Reputation: 1044
I've got a weird issue I'm assuming is simple to fix.
I'm simplifying things for context, but let's say I've got following code:
$schval = "Val";
$schbind = "%".$schval."%";
$sql = "SELECT Col1, Col2, Col3 FROM MyTable WHERE Col1 LIKE :schbind";
$stmt = $conn->prepare($sql);
$stmt->bindparam(':schbind',$schbind);
$stmt->execute();
$rows = $stmt->fetchAll();
This works.
However if I want to use the :schbind more than once in the query, by changing the $sql variable, as so:
$sql = "SELECT Col1, Col2, Col3 FROM MyTable WHERE (Col1 LIKE :schbind OR Col2 LIKE :schbind)";
The query fails in the sense that it returns no rows.
Normal SQL logic tells me this should work, i.e. if the search value is found to match either Col1 or Col2, then return the row.
Why is this not working?
Upvotes: 0
Views: 462
Reputation: 4875
You cannot use one placeholder twice. You need to do it like this:
$stmt->bindparam(':schbind1',$schbind);
$stmt->bindparam(':schbind2',$schbind);
$sql = "SELECT Col1, Col2, Col3 FROM MyTable WHERE (Col1 LIKE :schbind1 OR Col2 LIKE :schbind2)";
You can read this post to get alternative solutions and further explanations: Use bound parameter multiple times
Upvotes: 2