可能让PHP MYSQL查询忽略WHERE子句中的空变量? [英] Possible to have PHP MYSQL query ignore empty variable in WHERE clause?

查看:160
本文介绍了可能让PHP MYSQL查询忽略WHERE子句中的空变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定如何执行此操作.基本上,我有一个用组合框填充的变量,然后通过where子句传递给MQSQL查询以形成过滤器.我需要做的是让用户将组合框保留为空,然后在where子句中忽略该变量.这可能吗?

Not sure how I can do this. Basically I have variables that are populated with a combobox and then passed on to form the filters for a MQSQL query via the where clause. What I need to do is allow the combo box to be left empty by the user and then have that variable ignored in the where clause. Is this possible?

,即此代码中的.假定填充$ value1的组合框为空,是否有任何方法可以忽略此组合,而仅应用第二个过滤器.

i.e., from this code. Assume that the combobox that populates $value1 is left empty, is there any way to have this ignored and only the 2nd filter applied.

$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);

感谢您的帮助. C

推荐答案

使用

$where = "WHERE user_id = '$username'";

if(!empty($value1)){
$where .= "and location = '$value1'";
}

if(!empty($value2 )){
$where .= "and english_name= '$value2 '";
}


$query = "SELECT * FROM moth_sightings $where";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);

这篇关于可能让PHP MYSQL查询忽略WHERE子句中的空变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆