Passing an array to a query using a WHERE clause

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

    More an example:

    $galleryIds = [1, '2', 'Vitruvian Man'];
    $ids = array_filter($galleryIds, function($n){return (is_numeric($n));});
    $ids = implode(', ', $ids);
    
    $sql = "SELECT * FROM galleries WHERE id IN ({$ids})";
    // output: 'SELECT * FROM galleries WHERE id IN (1, 2)'
    
    $statement = $pdo->prepare($sql);
    $statement->execute();
    

提交回复
热议问题