忽略MYSQL查询的空值

时间:2017-04-03 17:11:49

标签: php mysql

我有一个表格供用户输入一些信息。提交表单后,它应该使用用户输入的值查询数据库。

我的问题是,如果用户输入的某些值为null,则应从查询中删除。

这是我的代码:

if(isset($_POST['submit']))
{
include("../includes/header.php");
include ("../scripts/db/connect.php");

//Gets variables from $_POST
$negocio = $_POST['negocio'];
$imovel = $_POST['imovel'];
$distrito = $_POST['distrito'];
$concelho = $_POST['concelho'];
$freguesia = $_POST['freguesia'];

$query = "SELECT * FROM imoveis WHERE negocio = $negocio and imovel = $imovel and distrito = $distrito and concelho = $concelho and freguesia = $freguesia";
}

想象一下,如果$negocio$imovel$concelho$freguesia等于null,则查询应为:

$query = "SELECT * FROM imoveis WHERE distrito = $distrito;

我该怎么做?

2 个答案:

答案 0 :(得分:3)

  

根据设置的值动态生成查询字符串   或者不是null,而不是使用该查询

在单独的文件中运行此代码,在删除或添加任何变量的注释后,您将理解这一点($ name,$ street,$ address或$ qualification)

// you will see query will change depending on the set variable,
//I am using these name you can use any name for your variable

$name='my name';
//$address='some where on earth';
$street='this is my street';
//$qualification='i am very much qualified';

//now create the array only with the values which are not empty or not nul,
//I am using empty you can use null if you want with this example you can use any thing.
if(!empty($name)) $query_string_second_part[]=" AND name = '$name'";
if(!empty($address)) $query_string_second_part[]=" AND address = '$address'";
if(!empty($street)) $query_string_second_part[]=" AND street = '$street'";
if(!empty($qualification)) $query_string_second_part[]=" AND qualification = '$qualification'";

//hand type the first part for the query
$query_string_First_Part= "SELECT * FROM myTableName WHERE";
//Implode the array, if you want to see how it look like use echo,
$query_string_second_part= implode(" ", $query_string_second_part);
//as you can see we are adding AND with every value, so we need to remove the first AND
//with one space
//Make sure you give space in the second parameter. else it wont work means "" not correct but " " is correct
//Hint --> use one space in between the double qoutes
$query_string_second_part=  preg_replace("/AND/", " ", $query_string_second_part, 1);

//Join the first and second part together to create a full query
$query_string=$query_string_First_Part.$query_string_second_part;
echo ($query_string);//see how our query look like at the moment

答案 1 :(得分:0)

您可以为每个子句添加输入空检查。例如,您执行此操作的地方:

distrito = $distrito

您可能会这样做:

(distrito = $distrito or $distrito IS NULL)

或者也许:

(distrito = $distrito or $distrito = '')

根据数据类型,用于构建查询的实际输入等。在手动构建这样的查询时可能需要进行一些调整和调试(我怀疑使用带有查询参数的预处理语句会使这个更干净,以及虽然更安全),但这个想法无论如何都是一样的。

基本上,您指示它根据值匹配行,或者根据缺少值匹配行。因此,对于任何给定子句,如果提供的值为null / empty,则所有行都匹配,并且该子句变得没有实际意义。