Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use prepared statements in queries with an IN clause in PHP [duplicate]

I need to make a simple query

$array_of_ids = array();
//poulate $array_of_ids, they don't come from another db but from Facebook
//so i can't use a subquery for the IN clause
$wpdb->prepare("SELECT id from table where id IN (%d, %d)", $array_of_ids [0], $array_of_ids [1]);

The question is, if i have 200 elements in the array, what is the correct way to handle this?Do i have to manually build the query with 200 %d? I need this query because i must "sync" my database with facebook data and i have to check if the user i have in the db are present, update those that are present, insert new users and delete those that are not my friend.

like image 693
Nicola Peluchetti Avatar asked Oct 07 '22 21:10

Nicola Peluchetti


1 Answers

If you know for certain that the array elements are numeric:

$wpdb->prepare("SELECT id FROM table WHERE id IN ("
  . implode(',',$array_of_ids) . ")");

Otherwise, you can use the vsprintf form of prepare to pass in the array of parameters:

$wpdb->prepare("SELECT id FROM table WHERE id IN ("
  . str_repeat("%d,", count($array_of_ids)-1) . "%d)" , $array_of_ids);
like image 52
eggyal Avatar answered Oct 12 '22 21:10

eggyal