1

I have an array of objects:

$arr = array('10', '12');

and i am running this query using PDO:

$stmt = $pdo->prepare("SELECT * from table WHERE user_sequence = :user_sequence");

i want to be able to have the query say WHERE user_sequence = :item1 OR user_sequence = :item2

item1, item2 etc being the objects from the array

how can i do this using PDO?

usually in MySQL, i would do:

$sql="SELECT * from table WHERE ";
foreach($array as $a) {
    $sql.="col = '".$a."' OR ";
}

but im not sure how to copy this theory in a PDO query

1
  • You would do the query as you have written it WHERE (user_sequence = :item1 OR user_sequence = :item2) and bind your variable accordingly. Commented Nov 11, 2015 at 22:32

1 Answer 1

1

You could do it like this:

$values = [ 'first value', 'second value', 'third value' ];

$conds = array_map(function() {
    return "user_sequence = ?";
}, $values);

$sql = "SELECT * from table WHERE " . implode(" OR ", $conds);

$stmt = $pdo->prepare($sql);
$stmt->execute($values);
Sign up to request clarification or add additional context in comments.

3 Comments

just tried this, im getting an error (Fatal error: Call to undefined method PDO::execute())
@charlie Sorry, I had a small mistake.
@charlie You should consider accepting more of the answers to your questions. It shows future visitors to the site which ones worked for you and also gives reputation points to both you and the person whose answer you accept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.