$name1 = @$_GET['search'] ;
$name = split(" +",$name1);
$query = "select * from table where field1 = '".$name[0]."'
and field2 = '".$name[1]."'
Order By `date` DESC";
我进行了类似的简单搜索,但如果$name[0]
和$name[1]
都有数据,则查询可以正常工作,如果$name[1]
为空,则查询失败。如何添加判断如果$name[1]
为空,隐藏and field2 = '".$name[1]."'
,并进行类似
$query = "select * from table where field1 = '".$name[0]."' Order By
日期DESC";
答案 0 :(得分:2)
您可以使用or
:
(and field2 = '".$name[1]."' or '".$name[1]."' = '')
答案 1 :(得分:1)
试试这个
if(!empty($name[0]) or !empty($name[1])){
$sql = "select * from table where ";
if($name[0]){
$fld1 = " field1 = '".$name[0]."'";
}
if($name[1]){
$fld2 = " field2 = '".$name[1]."'";
}
if($fld1 && $fld2)
{
$sql .= $fld1 ." and ".$fld2;
}
elseif($fld1){
$sql .= $fld1;
}
elseif($fld2){
$sql .= $fld2;
}
}
答案 2 :(得分:1)
如果你在PHP脚本中,这样做会更好
$query = "select * from table where field1 = '$name[0]'"
if ($name[1]) $query .= " and field2 = '$name[1]'";
$query .= 'order by date desc';
答案 3 :(得分:0)
$name[1]?'query of it exists':'query if it doesn't';