user2755541 user2755541 - 2 months ago 5
MySQL Question

Building mySQL Query with PHP params -- "first AND"

I'm trying to build an sql query with php where each GET variable (if set) gets appended to the query. So for example:

$dbQuery = "SELECT * FROM orders WHERE deleted = 0 AND ({$dueQ} {$paidQ} {$completedQ} {etc. etc. etc.}) ";


Where each parameter is created like so:

$due = $_GET['due'];
if (isset($due)) {
$dueQ = " AND due = '0'";
}


So I'm checking to see if each get parameter is set, then if it is, adding that string to the query.

My question is this...
How do I create the query such that the first parameter doesn't start with "AND"? Since I don't know which will be the first parameter to be appended to the query, I can't find a way to account for it not starting with "AND". Right now the query reads "AND due='0' AND...". Make sense?

Answer

You could add your parameters to an array, then implode() them with AND as the glue:

$params = array();
if (isset($_GET['due']))
    $params[] = "due = '0'";

if (isset($_GET['paid']))
    $params[] = "paid = '0'";

...etc...

$dbQuery = "SELECT ... WHERE deleted = 0 AND ".implode(' AND ', $params);
//SELECT ... WHERE deleted = 0 AND due = '0' AND paid = '0'
Comments