Passing an array to a query using a WHERE clause

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

    You may have table texts (T_ID (int), T_TEXT (text)) and table test (id (int), var (varchar(255)))

    In insert into test values (1, '1,2,3') ; the following will output rows from table texts where T_ID IN (1,2,3):

    SELECT * FROM `texts` WHERE (SELECT FIND_IN_SET( T_ID, ( SELECT var FROM test WHERE id =1 ) ) AS tm) >0
    

    This way you can manage a simple n2m database relation without an extra table and using only SQL without the need to use PHP or some other programming language.

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

    Safer.

    $galleries = array(1,2,5);
    array_walk($galleries , 'intval');
    $ids = implode(',', $galleries);
    $sql = "SELECT * FROM galleries WHERE id IN ($ids)";
    
    0 讨论(0)
  • 2020-11-21 09:29

    As Flavius Stef's answer, you can use intval() to make sure all id are int values:

    $ids = join(',', array_map('intval', $galleries));  
    $sql = "SELECT * FROM galleries WHERE id IN ($ids)";
    
    0 讨论(0)
  • 2020-11-21 09:31

    Safe way without PDO:

    $ids = array_filter(array_unique(array_map('intval', (array)$ids)));
    
    if ($ids) {
        $query = 'SELECT * FROM `galleries` WHERE `id` IN ('.implode(',', $ids).');';
    }
    
    • (array)$ids Cast $ids variable to array
    • array_map Transform all array values into integers
    • array_unique Remove repeated values
    • array_filter Remove zero values
    • implode Join all values to IN selection
    0 讨论(0)
  • 2020-11-21 09:32

    Use:

    select id from galleries where id in (1, 2, 5);
    

    A simple for each loop will work.

    Flavius/AvatarKava's way is better, but make sure that none of the array values contain commas.

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

    Besides using the IN query, you have two options to do so as in an IN query there is a risk of an SQL injection vulnerability. You can use looping to get the exact data you want or you can use the query with OR case

    1. SELECT *
          FROM galleries WHERE id=1 or id=2 or id=5;
    
    
    2. $ids = array(1, 2, 5);
       foreach ($ids as $id) {
          $data[] = SELECT *
                        FROM galleries WHERE id= $id;
       }
    
    0 讨论(0)
提交回复
热议问题