質問

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?

役に立ちましたか?

解決

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);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top