I’m writing a PHP script that builds an SQL query by concatenating the string and adding conditions to the WHERE clause as needed.
Would it be better practice to use WHERE 1=1 so that the first condition is satisfied and the script can just concatenate an AND x = 'y' to the query, or should I write the extra code to check if a clause has been added and if not, add the AND ?
The first solution allows for cleaner code in the script but just seems wrong to me.
Confusing question, I know. Let me know if I need to be more clear.
Rob
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: