Search code examples
phpmysqliprepared-statement

Use an array in a mysqli prepared statement: `WHERE .. IN(..)` query


Imagine we have a query:

SELECT * FROM somewhere WHERE `id` IN(1,5,18,25) ORDER BY `name`;

and an array of IDs to fetch: $ids = array(1,5,18,25)

With prepared statements it's adviced to prepare one statement and call it multiple times:

$stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id`=?;');
foreach ($ids as $id){
    $stmt->bind_params('i', $id);
    $stmt->exec();
}

But now I'll have to sort the results manually. Do I have any nice alternatives?


Solution

  • you could do it this way:

    $ids = array(1,5,18,25);
    
    // creates a string containing ?,?,? 
    $clause = implode(',', array_fill(0, count($ids), '?'));
    
    
    $stmt = $mysqli->prepare('SELECT * FROM somewhere WHERE `id` IN (' . $clause . ') ORDER BY `name`;');
    
    call_user_func_array(array($stmt, 'bind_param'), $ids);
    $stmt->execute();
    
    // loop through results
    

    Using this you're calling bind_param for each id and you have sorting done by mysql.