Re: Need help with PHP & MySQL

by "Darrell King" <darrell(at)webctr.com>

 Date:  Fri, 3 May 2002 21:36:07 -0400
 To:  <hwg-techniques(at)hwg.org>
 References:  D1C4FN01 ntlworld pieceoshit king pieceoshit2
  todo: View Thread, Original
When you have multiples like that, you need to first check whether there
should even by a WHERE in the query.  If all the clauses are empty, then the
WHERE stands alone and that is a BAD thing.

Try this:

$where_clause=Array();

if (isset($alpha)&&!empty($alpha)) $where_clause[] =" Alpha='$alpha' ";
if (isset($county)&&!empty($county)) $where_clause[] =" County='$country' ";
if (isset($cuisine)&&!empty($cuisine)) $where_clause[] =" Cuisine='$cuisine'
";
if (isset($price)&&!empty($price)) $where_clause[] =" Price='$price' ";

if (sizeof($where_clause)) {
 $final_where_clause=" WHERE ".join(" AND ",$where_clause);
}

$result=mysql_query(
 "SELECT *
  FROM Restaurants
  $final_where_clause
  ORDER BY Name
 ");

I didn't test it, again, of course, so watch for my typos!


D



----- Original Message -----
From: "Lisa Bradshaw" <zibbler(at)web-design-cs.com>


Okay, I'm getting closer. I used your suggestion and it worked great, so I
took it a step further to include the other elements in the form, then it
didn't work :-(   I get a warning that says: Warning: Supplied argument is
not a valid MySQL result resource. Here's the code I used. Maybe you can
spot something I did wrong?


if (isset($alpha)&&!empty($alpha)) $alpha_clause=" AND Alpha='$alpha' ";
else $alpha_clause='';

if (isset($county)&&!empty($county)) $county_clause="County='$county' ";
else $county_clause='';

if (isset($cuisine)&&!empty($cuisine)) $cuisine_clause=" AND
Cuisine='$cuisine' ";
else $cuisine_clause='';

if (isset($price)&&!empty($price)) $price_clause=" AND Price='$price' ";
else $price_clause='';

$result=mysql_query("SELECT * FROM
Restaurants WHERE $county_clause $alpha_clause $cuisine_clause
$price_clause ORDER BY Name");

HWG hwg-techniques mailing list archives, maintained by Webmasters @ IWA