Is it poor practice to build an SQL query using WHERE 1=1 AND
create an array of the conditions as you determine which ones you need. when you're ready to build the query, check if the array is empty... if it is not empty then print "WHERE" followed by the elements joined together with "AND"s.
edit
since you're using PHP, I'll give some example code:
<?php $conditions = array(); if($foo == "bar") { $conditions[] = "some_table.foo = 'bar'"; } if($show_future) { $conditions[] = "some_table.entry_date > NOW()"; } $sql_where = count($conditions) ? "WHERE " . implode(" AND ", $conditions) : ""; $sql = "SELECT * FROM some_table $sql_where;";?>
To expand of Ty W's answer, since you're using PHP:
$clauses = array();// Optionally add one or more clauses to the array like this:$clauses[] = "test = 2";// Now generate the WHERE clause:$sql = 'SELECT * FROM Table ';$sql .= count($clauses) ? ('WHERE ' . implode(' AND ', $clauses)) : '';