简体   繁体   English

如何从php中的数组进行SQL查询?

[英]How to make sql query from an Array in php?

Please tell me how can we make sql query from array is it possible? 请告诉我如何才能从数组进行sql查询?

This is my code       
$myString = "Food,FastFood,Chinese";
        $myArray = explode(',', $myString);
        print_r($myArray);

This is output of above code: 这是上面代码的输出:

Array
(
    [0] => Food
    [1] => FastFood
    [2] => Chinese
)

My question is how can I make sql query from this array in php like 我的问题是我怎样才能像这样在php中从该数组进行sql查询

$sql="Select * from table where FoodCategories=$Food OR FoodCategories=$FastFood OR FoodCategories=$Chinese ";

Please help me out. 请帮帮我。

try this 尝试这个

$string="Food,FastFood,Chinese";
$array=explode(',', $string);
$array = implode("','",$array);
echo $query="Select * from table where FoodCategories IN ('".$array."')";

You could create an SQL Statement with an IN-Condition. 您可以使用IN条件创建一个SQL语句。 Check the official doc from MySQL - MySQL IN-Condition . 从MySQL- MySQL IN-Condition查看官方文档。

EDIT : This would be your new query: 编辑 :这将是您的新查询:

// you first have to implode your array and add quotes for each array item
$string = "'" . implode("','", $myArray) . "'";
// now you can create your new query
$sql = "Select * from table where FoodCategories IN ($string)";

You can use in 你可以用in

Try the following 尝试以下

$data = "'".implode("','",$myString)."'";
sql="Select * from table where FoodCategories in($data)";

Try this with easy way :) 用简单的方法试试这个:)

$myString =array("Food","FastFood","Chinese");
// make them together with ', '
$userStr = implode("', '", $myString );
$query="SELECT * FROM table WHERE FoodCategories in ('$userStr')";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM