繁体   English   中英

PHP中的MySQL查询条件中的数组

[英]MySQL query in PHP with an array in the condition

我正在PHP文件中进行MySQL查询。 我有一个包含多个国家/地区名称的数组($ country),我想从我的表中选择这些国家/地区的行。

$ country是以下数组:

Array
(
    [0] => Afghanistan
    [1] => Armenia
    [2] => Bhutan
)

我正在使用以下代码:

$result = mysqli_query($con,"SELECT * 
                             FROM table1 
                             WHERE table1.country='".$country."'");

但是,以下声明适用于唯一的国家/地区:

 $result = mysqli_query($con,"SELECT * FROM table1 WHERE table1.country='".$country[1]."'");

但它不起作用,我尝试:$ result的mysqli_num_rows()它表示参数是booelan(这是因为查询失败并返回false)。 有谁知道错误是什么?

这是table1结构:

在此输入图像描述

使用可以像这样使用IN

// Array should look like this.
// $country = array('spain', 'UK', 'Germany');

$result = mysqli_query($con, "SELECT * FROM table1 WHERE table1.country IN ('". implode("' , '", $country) . "')");

PS。 不要在答案中使用数组,因为您可能会得到空的结果。

使用IN

请注意您的国家/地区数据,例如$country = ['india', 'canada'];

$result = mysqli_query($con,"SELECT * FROM table1 WHERE table1.country IN('".$country."')");

您无法将数组传递给查询。 您可以使用IN将不同的逗号分隔值传递给查询。 首先,您必须获取每个数组条目并使用逗号连接它:

//initialize the list
$countries = "";
foreach($country as $a){
    //add each country wrapping it in single quotes
    $countries .= "'".$a."',";
}
//remove the last comma that is not necessary
rtrim($countries,",");
//build the query
$sql = "SELECT * FROM table1 WHERE table1.country IN ($countries)";
//run the query
$result = mysqli_query($con,$sql);

请注意,构建$ countries我已在每个元素周围放置单引号。 原因是我将字符串传递给数据库。 在整数的情况下,这不是必需的

暂无
暂无

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

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