【问题标题】:How to make sql query from an Array in php?如何从 php 中的数组进行 sql 查询?
【发布时间】:2018-04-11 08:37:45
【问题描述】:

请告诉我如何从数组中进行 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 ";

请帮帮我。

【问题讨论】:

  • 为什么不能用IN?
  • Select * from table where FoodCategories IN ($myString) 将产生相同的结果
  • 我是php新手,不懂IN?
  • IN 与 php 无关。它是 sql。而IN是sql新手最基本的概念
  • 你能给我举个例子吗?我该如何解决这个问题?

标签: php mysql sql arrays


【解决方案1】:

试试这个

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

【讨论】:

  • 你怎么又内爆了?
【解决方案2】:

您可以创建带有 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)";

【讨论】:

  • 错误,字符串中的值没有引号!
  • @u_mulder 对,谢谢...抱歉 - 代码现在已编辑。
  • 你怎么又内爆了?
  • 因为我想在 $myArray.此代码生成以下 SQL 语句:Select * from table where FoodCategories IN ('Food', 'FastFood', 'Chinese')
  • @BenjaminBur 你可以使用 str_replace。无需再次内爆。
【解决方案3】:

你可以使用in

试试下面的

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

【讨论】:

  • 错误,字符串中的值没有引号!
  • @u_mulder 谢谢。编辑了答案
  • 你怎么又内爆了?
【解决方案4】:

用简单的方法试试这个:)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多