PHP: Safely prepare a string for a PDO SQL statement using replace?

Solution:

When handling a variable number of parameters, it’s best to use ? placeholders. For example:


$placeholders = implode(',', array_fill(0, count($values), '?'));
$query = "SELECT field FROM my_table WHERE id IN ($placeholders)";
$stmt = $pdo->prepare($query);
$stmt->execute($values);

If the column names themselves are dynamic (as in an INSERT statement), you’ll still need string substitution. In that case, always whitelist column names to avoid SQL injection.

For the values being inserted, you can safely rely on placeholders. Just make sure to convert the array to a plain numeric one, since ? placeholders can’t be mapped from associative arrays:


$values = array_values($params);