[ciapug] Building a Where Clause from an Array
Chris Hettinger
ciapug@cialug.org
Fri, 14 May 2004 16:07:38 -0500
Okay ... I'm sure I can do this but it's just not clicking today. Please
HELP! :)
I have these 4 variables that I want to use in a where clause in my SQL
query. The thing is, it's a situation where it a 1 or more of the fields
will have a value... so here is my psydocode:
// populated from a form
$lname
$fname
$patientid
$caseid
/*
* for this example assume
* $lname = ''
* $fname = 'chris'
* $patientid = '150'
* $caseid = ''
*
*/
// put these into a array
$Params = array{
"lname" => $lname,
"fname" => $fname,
"patientid" => $patientid,
"caseid" => $caseid
);
// I count the number of values in the array
// so I know I have 2 values.
$sql = "SELECT * FROM myTable";
// Here I want to loop through the 'Params' array where
// a 'key' has a 'value' and then build a where clause
// if there is only 1 value
$sql .= " WHERE key = 'value'";
// if there is more than 1 value, use AND in the clause
$sql .= " AND WHERE key = 'value'";
$sql .= " ORDER BY lname ASC";
... Thanks
-ch