小编典典

可能让PHP MYSQL查询忽略WHERE子句中的空变量?

mysql

不知道我该怎么做。基本上,我有一个用组合框填充的变量,然后通过where子句传递给MQSQL查询以形成过滤器。我需要做的是让用户将组合框留空,然后在where子句中忽略该变量。这可能吗?

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

$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


阅读 402

收藏
2020-05-17

共1个答案

小编典典

采用

$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);
2020-05-17