Passing an array to a query using a WHERE clause

后端 未结 18 1017
情歌与酒
情歌与酒 2020-11-21 09:03

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:



        
18条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 09:45

    Basic methods to prevent SQL injection are:

    • Use prepared statements and parameterized queries
    • Escaping the special characters in your unsafe variable

    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()

提交回复
热议问题