Passing an array to a query using a WHERE clause

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

    For MySQLi with an escape function:

    $ids = array_map(function($a) use($mysqli) { 
        return is_string($a) ? "'".$mysqli->real_escape_string($a)."'" : $a;
      }, $ids);
    $ids = join(',', $ids);  
    $result = $mysqli->query("SELECT * FROM galleries WHERE id IN ($ids)");
    

    For PDO with prepared statement:

    $qmarks = implode(',', array_fill(0, count($ids), '?'));
    $sth = $dbh->prepare("SELECT * FROM galleries WHERE id IN ($qmarks)");
    $sth->execute($ids);
    

提交回复
热议问题