[英]Create Dynamic AND clause in mysql query using PHP
I am writing SQL Query based on array values but I am getting the wrong result. 我在写基于数组值的SQL查询,但是得到错误的结果。
For Example if my array values are ['PAK','USA'] then Query should be:- 例如,如果我的数组值为['PAK','USA'],则查询应为:-
Select * From `search` WHERE country = 'PAK' AND country = 'USA'
and if array values are ['USA','China'] then Query should be:- 如果数组值为['USA','China'],则查询应为:-
Select * From `search` WHERE country = 'USA' AND country = 'China'
and so on.. 等等..
I am doing this but I am getting the wrong result like this:- 我正在这样做,但我得到这样的错误结果:
SELECT * FROM `search` WHERE country = '' AND country = 'Pakistan' AND country = 'United States'
I am wondering why country = '' is always adding at the beginning of Query.. This is why I am getting the wrong result. 我想知道为什么country =''总是在查询的开头添加。这就是为什么我得到错误的结果。 Please help me out. 请帮帮我。 Thanks in advance.. Below is my code.. 预先感谢..下面是我的代码..
PHP 的PHP
$query_parts = array();
foreach($_POST['countryArray'] as $array){
$query_parts[] = "'".$array."'";
}
$string = implode(' AND country = ', $query_parts);
//echo $string;
$query = "SELECT * FROM `search` WHERE country = {$string}";
echo $query;
The code is fine. 代码很好。
But, blank elements from array are not restricted. 但是,数组中的空白元素不受限制。
The array $_POST['countryArray']
has a blank element. 数组$_POST['countryArray']
有一个空白元素。
You can filter it with array_filter() : 您可以使用array_filter()对其进行过滤:
$_POST['countryArray'] = array_filter($_POST['countryArray']);
Final Code: 最终代码:
$query_parts = array();
$_POST['countryArray'] = array_filter($_POST['countryArray']);
foreach($_POST['countryArray'] as $array){
$query_parts[] = "'".$array."'";
}
$string = implode(' AND country = ', $query_parts);
//echo $string;
$query = "SELECT * FROM `search` WHERE country = {$string}";
echo $query;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.