yoano yoano - 7 months ago 17
SQL Question

MySQL and PHP: how to fetch multiple ID's in an array containing the ID's

I have multiple ID's stored in a variable. This array can become long (+400 ID's). How do I fetch the data from these ID's in MySQL (PDO)?

I could do it via this:


"select * from info WHERE `id` IN ('1,2,3,4,5')"


But that's unsafe (SQL injection) and maybe not performant. Any suggestions to handle this problem?

Answer
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
    SELECT *
    FROM galleries
    WHERE id IN ($in);
SQL;
$statement = $pdo->prepare($select);
$statement->execute($ids);

source