This question already has answers here:
Can I bind an array to an IN() condition?
                                
                                    (21个回答)
                                
                        
                                2年前关闭。
            
                    
谁能看到我如何使用String而不是Numerical来表示此语句,

我试图在$ delivery =“ ALL”时拉出所有带有$ delivery的行,但我只能拉出1个单个变量,如果我想拉一个数组,我不能,因为我将Array转换num转换为字符串,

$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在$ VAR,$ VAR,$ VAR中选择$ VAR的位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50698548/

10-09 00:50