Exploring PHP arrays and SQL
The array handling functions of PHP are exceptionally powerful, and well worth exploring. In this section, we explore some widely used techniques that are helpful in building SQL statements.
One situation that is very common is the need for a SQL statement that will have a variable number of WHERE
clauses, depending on the particular circumstances. For simplicity, suppose that all the conditions have to be joined together using AND
.
Of course, we could write a conditional statement each time another item is to be added to the SQL. But it would be clumsy because the logic would be different for the first condition actually required, which needs to be preceded by WHERE
and the other cases, which need to be preceded by AND
. A much simpler approach is provided by PHP array processing.
For each possible condition we assign the conditional clause to an array, using PHP's ability to allocate the next array element by coding square brackets with nothing inside them. So...