Passing an array to a query using a WHERE clause

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

提交回复
热议问题