John Davidson

php - WHERE clause confusion with PDO


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.

My Answer:
>prepare("SELECT * FROM table WHERE column1 = :value OR column2 = :value OR column3 = :value");
$stmt->bindParam(':value', $value);

You can use the IN clause to match one value against multiple columns at once. Here's an example:

$stmt = $dbh->prepare("SELECT * FROM table WHERE :value IN (column1, column2, column3)");
$stmt->bindParam(':value', $value);

This way, you only need to bind the value once and it will be checked against all three columns in the query.

Rate this post

4 of 5 based on 9767 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us