簡體   English   中英

如何從php中的數組進行SQL查詢?

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

請告訴我如何才能從數組進行sql查詢?

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

這是上面代碼的輸出:

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

我的問題是我怎樣才能像這樣在php中從該數組進行sql查詢

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

請幫幫我。

嘗試這個

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

您可以使用IN條件創建一個SQL語句。 從MySQL- MySQL IN-Condition查看官方文檔。

編輯 :這將是您的新查詢:

// 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)";

你可以用in

嘗試以下

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

用簡單的方法試試這個:)

$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