Last updated on October 28th, 2021 at 09:18 pm
Other than using bind in SQL, this is the old school way to solve the SQL query to prevent injection attack
Sample Code
// a sample list of values to use in IN():
$values = [1,4,10,'12a','xy\'z'];
// VERSION 1. For integers: make sure all array elements are integers
$in = implode(',', array_map('intval', $values));
// VERSION 2. For strings: apply PDO::quote() function to all elements
$in = implode(',', array_map([$pdo, 'quote'], $values));
// VERSION 3. Custom sanitization: allow only letters and numbers in strings
$in = implode(',', array_map(function($v) {
return "'" . preg_replace('/[^a-zA-Z0-9]/', '', $v) . "'";
}, $values));
// now I can safely inject the values into SQL:
$stmt = $pdo->query("SELECT username FROM userInfoTable WHERE username IN ($in)");