gpt4 book ai didi

php - MySQL PHP 中的 where 子句中的 if 条件

转载 作者:行者123 更新时间:2023-11-29 06:36:42 25 4
gpt4 key购买 nike

我在 PHP 中有一个变量。我想在 MySQL 查询中检查我的 PHP 变量,如果它不为 null,则在 where 子句中使用它。

select * from T1
where post = "news" and $city = cityname and $city is not null

$city 是 PHP 变量。

$city 为空时,我遇到问题,它应该显示所有新闻帖子,但它什么也不返回。

这是我的 table : enter image description here

最佳答案

由于 $city 是一个 PHP 变量,如果它是 NULL 那么当您在查询中回显它时,您将什么也得不到。这将产生无效的查询;它看起来像这样:

select * from T1
where post = "news" and = cityname and is not null

要实现此功能,您需要将查询中的 $city 用引号引起来,然后不要将其与 NULL 进行比较,而是将其与空字符串进行比较,即

select * from T1
where post = "news" and ('$city' = cityname or '$city' = '')

请注意,对于此用例,正确的逻辑运算符是 or

正如评论中所指出的,您应该查看准备好的语句。这个问题有一些非常有用的信息:How can I prevent SQL injection in PHP?

关于php - MySQL PHP 中的 where 子句中的 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517726/

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