开发者

php select from where and problem

开发者 https://www.devze.com 2023-02-13 07:28 出处:网络
$name1 = @$_GET[\'search\'] ; $name = split(\" +\",$name1); $query = \"select * from table where field1 = \'\".$name[0].开发者_如何学Python\"\'
$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 BydateDESC";


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';
0

精彩评论

暂无评论...
验证码 换一张
取 消