gpt4 book ai didi

php - Mysql SELECT WHERE $VAR IN $VAR,$VAR,$VAR

转载 作者:行者123 更新时间:2023-11-29 17:30:34 26 4
gpt4 key购买 nike

任何人都可以看到我如何在该语句中使用字符串而不是数字,

我试图在 $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"));

所以我的问题是,如何解决这个问题,让 select 函数与 $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]);

关于php - Mysql SELECT WHERE $VAR IN $VAR,$VAR,$VAR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com