cj333
cj333

Reputation: 2609

php select from where and problem

$name1 = @$_GET['search'] ;
$name = split(" +",$name1);
$query = "select * from table where field1 = '".$name[0]."'
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";

Upvotes: 0

Views: 1092

Answers (4)

S L
S L

Reputation: 14328

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;
    }

 }

Upvotes: 1

azat
azat

Reputation: 3565

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

Upvotes: 1

VladTheImpaler
VladTheImpaler

Reputation: 138

$name[1]?'query of it exists':'query if it doesn't';

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 121007

You can do it with an or:

(and field2 = '".$name[1]."' or '".$name[1]."' = '')

Upvotes: 2

Related Questions