where子句,不带空变量

时间:2014-10-26 07:45:34

标签: php mysql sql

下面的一些变量(us1或sp1 ..)可能具有空值(客户有可能不填写相应的文本视图)。我怎么能语法"哪里"只有" not null"变量;例如,当us1不为null且sp1为null时,"其中"条款必须是:" customer.username1 =' us1' " 提前致谢

$us1 = $_POST['username1'];
$sp1 = $_POST['startPoli1'];

SELECT `username1`,`startPoli1`, `finalPoli1`,`weight1` ,`phone1` 
 FROM customer ,registration1 
 where  customer.startPoli1 = 'sp1' and customer.username1 = 'us1'

3 个答案:

答案 0 :(得分:1)

以这种方式写下条件:

WHERE ('sp1' IS NULL OR customer.startPoli1 = 'sp1')
AND ('us1' IS NULL OR customer.username1 = 'us1')

答案 1 :(得分:0)

像这样:

$us1 = $_POST['username1'];
$sp1 = $_POST['startPoli1'];

$sql = "SELECT `username1`,`startPoli1`, `finalPoli1`,`weight1` ,`phone1` 
 FROM customer ,registration1 where 1=1 ";

if($sp1 != null)
   $sql += "and customer.startPoli1 = 'sp1'";
if($us1 != null) 
   $sql += "and customer.username1 = 'us1'";

答案 2 :(得分:0)

我认为 - 这是有问题的错误。忘记了$ sp1和$ us1是变量

$us1 = $_POST['username1'];
$sp1 = $_POST['startPoli1'];

$sql = "SELECT `username1`,`startPoli1`, `finalPoli1`,`weight1` ,`phone1` 
 FROM customer ,registration1 where 1=1 ";

if($sp1 != null)
   $sql += "and customer.startPoli1 = '" + $sp1 + "'";
if($us1 != null) 
   $sql += "and customer.username1 = '" + $us1 + "'";