简体   繁体   中英

How to write sql query in php with if statement in WHERE

How do I write a SQL query with an if statement in the WHERE part of a query?

Here is my sql:

$sql = 'SELECT First, Second, 
           Third,Fifth, Status, Isik_id, Comments, Code
    FROM Persons WHERE  Status = 1 && Third = "'.$whoislogged.'" ORDER BY RAND()  LIMIT 1';

The Third = "'.$whoislogged.'" is a word what comes from session.

If $whoislogged exists and is equal to Third then the query should be like:

$sql = 'SELECT First, Second, Third,Fifth, Status, Isik_id, Comments, Code
        FROM Persons 
WHERE  Status = 1 && Third = "'.$whoislogged.'" ORDER BY RAND()  LIMIT 1';

But if the $whoislogged dosent appear then the query should be like:

 $sql = 'SELECT First, Second, 
           Third,Fifth, Status, Isik_id, Comments, Code
    FROM Persons WHERE  Status = 1 ORDER BY RAND()  LIMIT 1';

So how can I put all this into one query?

Simply make a new variable that contains the Third statement

if ( !empty($whoislogged) ) $third = "AND Third = ". $whoislogged;
else $third = "";

$sql = 'SELECT First, Second, 
           Third,Fifth, Status, Isik_id, Comments, Code
    FROM Persons WHERE  Status = 1 '. $third .' ORDER BY RAND()  LIMIT 1';

It is not the most efficient way but it works

You can handle it in query itself.

WHERE  Status = 1 and if(Third = "'.$whoislogged.'", Third = "'.$whoislogged.'" , 1=1)

the condition part will check third is match with $whoislogged if it's true then add id as condition otherwise omit this condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM