SQL,如果 PHP 值为空,则忽略 where 原因 [英] SQL, ignore where cause if PHP value is empty

查看:79
本文介绍了SQL,如果 PHP 值为空,则忽略 where 原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 PHP 值为空,有谁知道如何让 mysql 查询忽略某个 where 条件.我正在尝试使用许多严格的 where 条件来创建一个高级搜索引擎来过滤搜索,但是如果 PHP 值为空,我希望 SQL 忽略一些 where 原因.例如:

Does anyone know how to get a mysql query to ignore a certain where condition if the PHP value is empty. I am trying to create an advance search engine with many strict where conditions to filter search, but would like the SQL to ignore some of the where causes if the PHP value is empty. For example:

$condition_1 = ' ';
$condition_2 = 'Random';
mysql_query("SELECT something FROM table WHERE row_1='$condition_1' &&     row_2='$condition_2'")

查询中将有 15 个 where 原因,因此任何涉及针对不同搜索组合进行多个查询的操作都是不可行的.

There will be 15 where causes in the query, so anything that involves making multiple queries for different combination of searches is not doable.

$condition_1 为空,只会向 row_1 中没有值的人显示结果,但我只想让查询在 PHP 值 $condition_1 为空时忽略 row_1 条件.我该怎么做?

$condition_1 is empty and will show results to only those with no value in row_1 , but I just want to have the query ignore the row_1 condition when the PHP value, $condition_1, is empty. How would I do this?

推荐答案

你可以动态构造你的 where 条件,注意这在两个条件都为空的情况下也有效

You can construct your where condition dynamically, note that this also works if both conditions are empty

$sql = "SELECT something FROM table where 1 ";

if(trim($condition_1) != '')
    $sql .= " AND  row_1='$condition_1'";

if(trim($condition_2) != '')
    $sql .= " AND  row_2='$condition_2'";

mysql_query($sql);

这篇关于SQL,如果 PHP 值为空,则忽略 where 原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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