0
$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";

1

4 Answers 4

2

You can do it with an or:

(and field2 = '".$name[1]."' or '".$name[1]."' = '')
Sign up to request clarification or add additional context in comments.

Comments

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

 }

Comments

1

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

2 Comments

what if there will be 3 parts?
I write simple part, if there will be 3 parts I can write some function joinAnd() and use it
0
$name[1]?'query of it exists':'query if it doesn't';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.