mysql选择$var中的$var,$var,$var

xeufq47z  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(417)

这个问题在这里已经有答案了

我可以将数组绑定到in()条件吗(21个答案)
两年前关门了。
有人知道我怎么用字符串来代替数字吗,
当$delivery=“all”时,我试图用$delivery拉取所有行,但我只能拉1个变量,如果我想拉一个数组,我不能,因为我得到数组转换num到string,

$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,
我真的卡住了。如果有人能帮忙的话
谢谢您。

hs1rzwqc

hs1rzwqc1#

使用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]);

相关问题