mardi 4 août 2015

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

How to i have to write SQL qery with 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.'"

The $whoislogged = "is a word what comes from session";

If $whoislogged exist and does equal to Third then the query shoul be like:

If Third = "'.$whoislogged.'" this is true then the sql to be: $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?




Aucun commentaire:

Enregistrer un commentaire