Passing an array to a query using a WHERE clause

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

    We can use this "WHERE id IN" clause if we filter the input array properly. Something like this:

    $galleries = array();
    
    foreach ($_REQUEST['gallery_id'] as $key => $val) {
        $galleries[$key] = filter_var($val, FILTER_SANITIZE_NUMBER_INT);
    }
    

    Like the example below:enter image description here

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

    I.e. now you should safely use $query = "SELECT * FROM galleries WHERE id IN ({$galleryIds})";

提交回复
热议问题