Passing an array to a query using a WHERE clause

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

提交回复
热议问题