简体   繁体   English

如何在WHERE中使用if语句在php中编写SQL查询

[英]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? 如何在查询的WHERE部分中使用if语句编写SQL查询?

Here is my sql: 这是我的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. Third = "'.$whoislogged.'"是来自会话的词。

If $whoislogged exists and is equal to Third then the query should be like: 如果$ whoislogged存在并且等于Third,则查询应类似于:

$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: 但是,如果出现$ whoislogged剂量,则查询应类似于:

 $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 只需创建一个包含Third语句的新变量

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. 条件部分将检查第三个条件是否与$ whoislogged匹配,然后添加id作为条件,否则忽略此条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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