SQL, ignore where cause if PHP value is empty

﹥>﹥吖頭↗ 提交于 2019-12-11 10:58:57

问题


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'")

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 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?


回答1:


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);


来源:https://stackoverflow.com/questions/23310611/sql-ignore-where-cause-if-php-value-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!