Jay -

How 'bout this?

$init = 1;
$query = "SELECT foo ";
$query .= "FROM bar WHERE";
if ($init AND isset($var1)) {
  $query .= "WHERE thus = '" . $var1 . "' ";
  $init = 0;}

if ($init AND isset($var2)) {
  $query .= "WHERE thus = '" . $var2 . "' ";
  $init = 0;}
elseif (isset($var2)) {
  $query .= "AND WHERE thus = '" . $var2 . "' ";
  $init = 0;}  

if ($init AND isset($var3)) {
  $query .= "WHERE thus = '" . $var3 . "' ";
  $init = 0;}
elseif (isset($var3)) {
  $query .= "AND WHERE thus = '" . $var3 . "' ";
  $init = 0;}

if ($init AND isset($var4)) {
  $query .= "WHERE thus = '" . $var4 . "' ";
  $init = 0;}
elseif (isset($var4)) {
  $query .= "AND WHERE thus = '" . $var4 . "' ";
  $init = 0;}

... you could even make all of those if...elseif's into a function.

Chip

-----Original Message-----
From: Jay Blanchard [mailto:[EMAIL PROTECTED]]
Sent: Wednesday, August 28, 2002 1:51 PM
To: [EMAIL PROTECTED]
Subject: [PHP] Building a query on multiple variables, how to test for
which variables are valid?


So these 4 variables walk into a bar.... :^]

I have a form with 4 drop downs. Each of these drop downs might have a value
and there is no order in which they might have a value. A query needs to
built (the WHERE and AND portions) that takes into account which ever
variables have been set. A user may choose a variable that would not be in
the first location.

$var1 = is not set
$var2 = is set
$var3 = is set
$var4 = is not set

(or any other combination) The query, of course, needs to be in order taking
into account the above example;

$query = "SELECT foo ";
$query .= "FROM bar ";
$query .= "WHERE thus = '" . $var2 . "' ";
$query .= "AND thus = '" . $var3 . "' ";

If three of the variables are set then there would need to be an additional
AND statement, etc. It would be foolhardy to construct an if or case
statement that would take into account each possible combination. I have
been thinking this through for an hour or so, but I am not seeing a clear,
elegant, and efficient piece of code. Has anyone done anything like this, or
does anyone have an idea of how this might be done?

TIA!

Jay

*****************************************************
* Texas PHP Developers Conf  Spring 2003            *
* T Bar M Resort & Conference Center                *
* New Braunfels, Texas                              *
* Contact [EMAIL PROTECTED]       *
*                                                   *
* Want to present a paper or workshop? Contact now! *
*****************************************************



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to