1

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?

2
  • I think your query is wrong. use AND instead of && Commented Apr 26, 2014 at 12:11
  • @dkakoti - && is equivalent to AND and an allowed operator in MySQL. Commented Apr 26, 2014 at 12:12

1 Answer 1

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

in the first condition is met sql will be "SELECT something FROM table where 1 AND row_1='$condition_1'", which works fine. Note that the expression 'WHERE 1 ' is just a dummy that always evaluates to true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.