php - Mysql SELECT WHERE $VAR IN $VAR,$VAR,$VAR
问题描述
任何人都可以看到我如何在这个语句中使用字符串而不是数字,
我试图在 $delivery="ALL" 时用 $delivery 拉所有行,但我只能拉 1 个单个变量,如果我想拉一个数组,我不能,因为我将数组转换为字符串,
$delivery_con = [];
if ($delivery==="collection") { $delivery_con[]="no";}
if ($delivery==="delivery") {$delivery_con[]="yes";}
if ($delivery==="local") {$delivery_con[]="yes local";}
if ($delivery==="either") {$delivery_con=["no","yes","yes local"];}
$query="SELECT *
FROM testdata
WHERE title LIKE ?
AND location LIKE ?
AND postcode LIKE ?
AND price >=?
AND price <=?
AND cond=?
AND catagory LIKE ?
AND delivery IN ?
ORDER BY $order $dir";
$stat=$db->prepare($query);
$stat->execute(array("%$searchfor%",
"%$location%",
"%$postcode%",
"$pricefrom",
"$priceto",
"$cond",
"%$catagory%",
"$delivery_con"));
所以我的问题是,如何才能让选择函数与 $variables 一起使用,
我真的卡住了。如果有人可以帮忙
谢谢你。
解决方案
使用 IN() SQL 运算符时,您需要?
手动创建一组并将它们放入查询中:
<?php
$delivery_con = [];
if ($delivery === "collection") {
$delivery_con[] = "no";
}
if ($delivery === "delivery") {
$delivery_con[] = "yes";
}
if ($delivery === "local") {
$delivery_con[] = "yes local";
}
if ($delivery==="either") {$delivery_con=["no","yes","yes local"];}
$in = str_repeat('?,', count($delivery_con) - 1) . '?';
$searchfor = "%$searchfor%";
$location = "%$location%";
$postcode = "%$postcode%";
$catagory = "%$catagory%";
$array1 = array($searchfor,$location,$postcode,$pricefrom,$priceto,$cond,$catagory);
$params = array_merge($array1, $delivery_con);
$query = "SELECT *
FROM testdata
WHERE title LIKE ?
AND location LIKE ?
AND postcode LIKE ?
AND price >=?
AND price <=?
AND cond=?
AND catagory LIKE ?
AND delivery IN ($in)
ORDER BY $order $dir";
$stat = $db->prepare($query);
$stat->execute([$params]);