Hacker News new | past | comments | ask | show | jobs | submit login

Lets say its 2001 and you are writing some hot e-commerce stuff in plain php. You want to filter data depending on multiple fields in the submitted form. If some field is there, you add one more "AND" clause to the "WHERE", like this: if (isset($_POST['product'])) { $query .= "AND product = " . $_POST['product']; }. So in order not to check every time if the added clause is the first one you start with "WHERE 1=1 ", as "WHERE AND ..." would not work.



Php has nothing like this?

In [1]: "... WHERE " + " AND ".join(str(i) for i in range(4))

Out[1]: '... WHERE 0 AND 1 AND 2 AND 3'

Very strange.


This will produce broken SQL on empty clauses list. Very strange.


You're quite right, but this is easily fixed. That doesn't change my question, since something like this is much easier that the other logic.


The easiest fix for this is the "WHERE 1=1" or "WHERE true"


I get how this isn't good. But how else would you handle multi-field filtering, keep all the ANDs and use (product_id = $1 OR $1 IS NULL) so the unset filters are no-op? That's ok as long as the query planner is smart enough.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: