PHP将数组解析并传递给where子句作为查询条件

  时间:2017-07-28
本文章向大家介绍php将数组解析并传递给where子句作为查询条件,需要的朋友可以参考一下。

给定一数组 $galleries = array(1,2,5),我想要一个SQL查询,它在WHERE子句中使用数组的值,如:

SELECT *
FROM galleries
WHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */

如何生成此查询字符串以用于MySQL?

 

最简单的方法:implode

数组元素的值是整型:

$query = "SELECT * FROM `$table` WHERE `$column` IN(".implode(',',$array).")";

数组元素的值是字符串:

$query = "SELECT * FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";

 

对于具有转义功能的MySQLi:

$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)");

对于准备好声明的PDO:

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

原文地址:http://www.manongjc.com/article/1983.html