Passing an array to a query using a WHERE clause

后端 未结 18 1062
情歌与酒
情歌与酒 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:52

    Using PDO:[1]

    $in = join(',', array_fill(0, count($ids), '?'));
    $select = <<prepare($select);
    $statement->execute($ids);
    

    Using MySQLi [2]

    $in = join(',', array_fill(0, count($ids), '?'));
    $select = <<prepare($select);
    $statement->bind_param(str_repeat('i', count($ids)), ...$ids);
    $statement->execute();
    $result = $statement->get_result();
    

    Explanation:

    Use the SQL IN() operator to check if a value exists in a given list.

    In general it looks like this:

    expr IN (value,...)
    

    We can build an expression to place inside the () from our array. Note that there must be at least one value inside the parenthesis or MySQL will return an error; this equates to making sure that our input array has at least one value. To help prevent against SQL injection attacks, first generate a ? for each input item to create a parameterized query. Here I assume that the array containing your ids is called $ids:

    $in = join(',', array_fill(0, count($ids), '?'));
    
    $select = <<

    Given an input array of three items $select will look like:

    SELECT *
    FROM galleries
    WHERE id IN (?, ?, ?)
    

    Again note that there is a ? for each item in the input array. Then we'll use PDO or MySQLi to prepare and execute the query as noted above.

    Using the IN() operator with strings

    It is easy to change between strings and integers because of the bound parameters. For PDO there is no change required; for MySQLi change str_repeat('i', to str_repeat('s', if you need to check strings.

    [1]: I've omitted some error checking for brevity. You need to check for the usual errors for each database method (or set your DB driver to throw exceptions).

    [2]: Requires PHP 5.6 or higher. Again I've omitted some error checking for brevity.

提交回复
热议问题