MySQL 查询:如果 REGEXP $var 为空,则选择全部?
$cities = "Amsterdam|Rotterdam|Den Haag"
$results = mysql_query("SELECT * FROM messages WHERE content REGEXP '$cities'");
上面的代码效果很好,但如果 $cities
为空,则不会选择任何内容。如果 $cities
没有值,我想选择所有行。我怎样才能做到这一点?谢谢!
$cities = "Amsterdam|Rotterdam|Den Haag"
$results = mysql_query("SELECT * FROM messages WHERE content REGEXP '$cities'");
The above code works great, but if $cities
is empty, nothing is selected. I'd like to select all rows if $cities
has no value. How can I achieve that? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在 php 中使用条件,当您的
$cities
变量为空时,它会删除 where 子句。或者,您可以使用匹配所有内容的正则表达式,例如/^/
,但它不是特别优雅。You will need to use a conditional in your php, which removes the where clause when your
$cities
variable is empty. Alternatively, you can use a regex that matches everything like/^/
, but it's not particularly elegant.您应该检查 $cities 是否为空。如果是,您可以将其替换为 .* (匹配所有内容)或从查询中删除 from 子句(会提高性能)
you should check to see if the $cities is empty. If it is you can replace it with .* (match everything) or remove the from clause from the query (would increase performance)
或者可能
Or probably