Advice On Building Dynamic MySQL Queries

From: Date: Thu, 19 Apr 2001 17:41:16 +0000
Subject: Advice On Building Dynamic MySQL Queries
Groups: php.db 
Request: Send a blank email to php-db+get-8723@lists.php.net to get a copy of this message
I am building a query from a search form. This is the code I have now: if (!empty($whereclause)) { $whereclause=urldecode($whereclause); $whereclause=stripslashes($whereclause); } extract($HTTP_POST_VARS); if (!empty($Price)) { if(empty($whereclause)) { $whereclause.="Price$Price"; } else { $whereclause.=" AND 'Price $Price"; } } if (!empty($Area)) { if(empty($whereclause)) { $whereclause.="Area LIKE '$Area'"; } else { $whereclause.=" AND Area LIKE '$Area'"; } } if (!empty($MLS_Number)) { if(empty($whereclause)) { $whereclause.="MLS_Number LIKE '$MLS_Number'"; } else { $whereclause.=" AND MLS_Number LIKE '$MLS_Number'"; } } if (!empty($File_Number)) { if(empty($whereclause)) { $whereclause.="File_Number LIKE '$File_Number'"; } else { $whereclause.=" AND File_Number LIKE '$File_Number'"; } } if (!empty($Description)) { if(empty($whereclause)) { $whereclause.="Description LIKE '%$Description%'"; } else { $whereclause.=" AND Description LIKE '%$Description%'"; } } $query="SELECT lid,Price,Address,Area,Description,File_Number,Realtor_First_name FROM listings LEFT JOIN areas ON (listings.aid=areas.aid) LEFT JOIN realtors ON (listings.rid1=realtors.rid) LEFT JOIN prop_types ON (listings.ptid=prop_types.ptid) LEFT JOIN prop_styles ON (listings.psid=prop_styles.psid) WHERE $whereclause order by Price ASC"; #echo "$query<br>"; if(empty($whereclause)) { echo"<center><h2>You Did Not Specify Anything To Search For!</h2><br> <a href=\"javascript:history.back()\">Back</a></center>"; } else { $results=$CONNECTION->Execute("$query") or DIE($CONNECTION->ErrorMsg()); $results__numRows=0; $results__totalRows=$results->RecordCount(); echo $results->Fields("aid"); echo "$query<br><br>"; while ($results__numRows<$results__totalRows) { #<SNIP> Display stuff $results__numRows++; $results->MoveNext(); } $results->Close(); } It Just became apparent that I am going to need to add a whole bunch more search criteria.. Does anyone have any advice/suggestions for getting rid of all those if statements? JD

« previous php.db (#8723) next »