$name1 = @$_GET['search'] ;
$name = split(" +",$name1);
$query = "select * from table where field1 = '".$name[0].开发者_如何学Python"'
and field2 = '".$name[1]."'
Order By `date` DESC";
I make a easy search like that, but if $name[0]
and $name[1]
all have data, the query can work, and if $name[1]
is empty, the query is failed. how to add a judge that if $name[1]
is empty, hidden and field2 = '".$name[1]."'
, and make the query like
$query = "select * from table where field1 = '".$name[0]."' Order By
dateDESC";
You can do it with an or
:
(and field2 = '".$name[1]."' or '".$name[1]."' = '')
Try this
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;
}
}
It will be better if you in your PHP script, do this check like this
$query = "select * from table where field1 = '$name[0]'"
if ($name[1]) $query .= " and field2 = '$name[1]'";
$query .= 'order by date desc';
$name[1]?'query of it exists':'query if it doesn't';
精彩评论