Passing an array to a query using a WHERE clause

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

    Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.

    I found that each string needed to be encapsulated in single quotes to work with the IN() function.

    Here is my solution

    foreach($status as $status_a) {
            $status_sql[] = '\''.$status_a.'\'';
        }
        $status = implode(',',$status_sql);
    
    $sql = mysql_query("SELECT * FROM table WHERE id IN ($status)");
    

    As you can see the first function wraps each array variable in single quotes (\') and then implodes the array.

    NOTE: $status does not have single quotes in the SQL statement.

    There is probably a nicer way to add the quotes but this works.

    0 讨论(0)
  • 2020-11-21 09:50

    Assuming you properly sanitize your inputs beforehand...

    $matches = implode(',', $galleries);
    

    Then just adjust your query:

    SELECT *
    FROM galleries
    WHERE id IN ( $matches ) 
    

    Quote values appropriately depending on your dataset.

    0 讨论(0)
  • 2020-11-21 09:50

    Below is the method I have used, using PDO with named placeholders for other data. To overcome SQL injection I am filtering the array to accept only the values that are integers and rejecting all others.

    $owner_id = 123;
    $galleries = array(1,2,5,'abc');
    
    $good_galleries = array_filter($chapter_arr, 'is_numeric');
    
    $sql = "SELECT * FROM galleries WHERE owner=:OWNER_ID AND id IN ($good_galleries)";
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(
        "OWNER_ID" => $owner_id,
    ));
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    0 讨论(0)
  • 2020-11-21 09:52

    Using PDO:[1]

    $in = join(',', array_fill(0, count($ids), '?'));
    $select = <<<SQL
        SELECT *
        FROM galleries
        WHERE id IN ($in);
    SQL;
    $statement = $pdo->prepare($select);
    $statement->execute($ids);
    

    Using MySQLi [2]

    $in = join(',', array_fill(0, count($ids), '?'));
    $select = <<<SQL
        SELECT *
        FROM galleries
        WHERE id IN ($in);
    SQL;
    $statement = $mysqli->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 = <<<SQL
        SELECT *
        FROM galleries
        WHERE id IN ($in);
    SQL;
    

    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.

    0 讨论(0)
  • 2020-11-21 09:52

    ints:

    $query = "SELECT * FROM `$table` WHERE `$column` IN(".implode(',',$array).")";
    

    strings:

    $query = "SELECT * FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";
    
    0 讨论(0)
  • 2020-11-21 09:52

    For MySQLi with an escape function:

    $ids = array_map(function($a) use($mysqli) { 
        return is_string($a) ? "'".$mysqli->real_escape_string($a)."'" : $a;
      }, $ids);
    $ids = join(',', $ids);  
    $result = $mysqli->query("SELECT * FROM galleries WHERE id IN ($ids)");
    

    For PDO with prepared statement:

    $qmarks = implode(',', array_fill(0, count($ids), '?'));
    $sth = $dbh->prepare("SELECT * FROM galleries WHERE id IN ($qmarks)");
    $sth->execute($ids);
    
    0 讨论(0)
提交回复
热议问题