6 ms·
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 som
by egormakarov 2y ago
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.
- freilanzer 2y agoPhp 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.
- egormakarov 2y agoThis will produce broken SQL on empty clauses list. Very strange.
- freilanzer 2y agoYou'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.
- paperplatter 2y agoThe easiest fix for this is the "WHERE 1=1" or "WHERE true"
- paperplatter 2y agoI 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.