I am building a SQL query that dynamically changes based on passed in $_GET parameters. I simply want to know if putting in a ‘dummy’ constraint is an ‘acceptable’ practice, so I do not have to check the SQL string for the existence of ‘where’ before I add new constraints (each time).
For example, the ‘dummy’ constraint’:
$sql = "select * from users u where u.id != 0";
Now, in each block where I determine if I have to add more constraints, I can just do:
if (!empty($uid))
$sql .= " and (u.id = {$uid})";
Instead of doing:
if (!empty($uid)) {
$sql .= strpos($sql, "where") === false ? " where " : " and ";
$sql .= " (u.id = {$uid})";
}
I’ve used that convention (although I usually use
WHERE 1=1 AND.) Depending on your RDBMS, using a column there could affect performance. For example, if you had an index that would otherwise be a covering index except for that column.Please make sure that you understand the potential pitfalls of this kind of dynamic SQL, but if it’s what you ultimately end up doing, adding that extra bit seems to make sense to me.