Given an array of ids $galleries = array(1,2,5)
I want to have a SQL query that uses the values of the array in its WHERE clause like:
Basic methods to prevent SQL injection are:
Using prepared statements and parameterized queries query is considered the better practice, but if you choose the escaping characters method then you can try my example below.
You can generate the queries by using array_map
to add a single quote to each of elements in the $galleries
:
$galleries = array(1,2,5);
$galleries_str = implode(', ',
array_map(function(&$item){
return "'" .mysql_real_escape_string($item) . "'";
}, $galleries));
$sql = "SELECT * FROM gallery WHERE id IN (" . $galleries_str . ");";
The generated $sql var will be:
SELECT * FROM gallery WHERE id IN ('1', '2', '5');
Note: mysql_real_escape_string, as described in its documentation here, was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()