gpt4 book ai didi

php - 如何在PHP中使用WHERE中的if语句编写sql查询

转载 作者:行者123 更新时间:2023-11-29 22:09:40 24 4
gpt4 key购买 nike

如何在查询的 WHERE 部分中编写带有 if 语句的 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';

Third = "'.$whoislogged.'" 是来自 session 的单词。

如果 $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';

但是如果 $whoislogged dosent 出现,那么查询应该是这样的:

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

那么我怎样才能将所有这些放入一个查询中呢?

最佳答案

您可以在查询本身中处理它。

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

条件部分将检查第三个是否与 $whoislogged 匹配,如果为 true,则添加 id 作为条件,否则忽略此条件。

关于php - 如何在PHP中使用WHERE中的if语句编写sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31804008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com