使用WHERE子句将数组传递给查询给定一个ID数组$galleries = array(1,2,5)我希望有一个SQL查询,它在WHERE子句中使用数组的值,如下所示:SELECT *FROM galleriesWHERE id = /* values of array $galleries... eg. (1 || 2 || 5) */如何生成这个查询字符串以便与MySQL一起使用?
4 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
使用PDO:[1]
$in = join(',', array_fill(0, count($ids), '?'));$select = <<<SQL SELECT * FROM galleries WHERE id IN ($in);SQL;$statement = $pdo->prepare($select);$statement->execute($ids);
使用MySQLi [2]
$in = join(',', array_fill(0, count($ids), '?'));$select = <<<SQL SELECT * FROM galleries WHERE id IN ($in);SQL;$statement = $mysqli->prepare($select);$statement->bind_param(str_repeat('i', count($ids)), ...$ids); $statement->execute();$result = $statement->get_result();
使用SQL IN()
运算符检查给定列表中是否存在值。
expr IN (value,...)
()
?
$ids
:
$in = join(',', array_fill(0, count($ids), '?'));$select = <<<SQL SELECT * FROM galleries WHERE id IN ($in);SQL;
$select
SELECT *FROM galleries WHERE id IN (?, ?, ?)
?
使用 IN()
带字符串的运算符
str_repeat('i',
str_repeat('s',
[1]:
[2]:
MMMHUHU
TA贡献1834条经验 获得超8个赞
$matches = implode(',', $galleries);
SELECT *FROM galleries WHERE id IN ( $matches )
添加回答
举报
0/150
提交
取消