tags:

views:

93

answers:

2

Right, so I have a set of dropdowns on my page. Depending on whether a value is selected, I want to add it to an SQL query string in PHP. Example:

select1: options("*" "op1", "op2)
select2: options("*" "op1", "op2)
select3: options("*" "op1", "op2)

'*' refers to anything. i.e the data should not be filtered by that query option. Now, how do I build the query for this quickly and simply? Currently, I have something like this:

$query='';
$found=0;
$op1=$_POST['select1'];
$op2=$_POST['select2'];
$op3=$_POST['select3'];

if($op1!='*')
{
$found=1;
$op1="'".$op1."'";
$query="WHERE op1=$op1 ";

}

if($op2!='*')
{$op2="'".$op2."'";
if($found==1)
    {
    $query=$query. "AND op2=$op2 ";
    }
else{
    $found=1;
    $query="WHERE op2=$op2 ";
    }
}

if($op3!='*')
{$op3="'".$op3."'";
if($found==1)
    {
    $query=$query. "AND op3=$op3 ";
    }
else{
    $found=1;
    $query="WHERE op3=$op3 ";
    }
}

Now, obviously, this is quite annoying to implement. Is there any easier method?

Thanks.

+2  A: 

I would have used a class MyQueryBuilder with following methods probably..

AddSelectionColumn(String ColumnName, string Alias)
AddTableSource(String TableName, String Alias)
AddTableJoin(String Table1, String Alias1, String Table2, String Alias2, String Col1, String Col2, JoinType Join)
AddFilterCondition(String ColumnName, String Alias, String Condition)

It might give a better control on the code...

Kangkan
A: 

I do a lot of this in my perl CGI scripts, and this is how I format it for simplicity / readability:

First, I use a separate variable for the where clause, and always set a condition of 1 = 1 so all subsequent conditions are "and" conditions:

my $whereClause      =<<ENDWHERESQL;
where
   1 = 1
ENDWHERESQL

if ( $op1 ne "*" )    { $whereClause .= "     and op1 = '".safeSQL($op1)."'\n"; }
if ( $op2 ne "*" )    { $whereClause .= "     and op2 = '".safeSQL($op2)."'\n"; }
if ( $op3 ne "*" )    { $whereClause .= "     and op3 = '".safeSQL($op3)."'\n"; }

then I use a simple function to protect against simple SQL injection attacks, because even though you are using drop down lists - someone could still put a "?op1=(evil sql)" on the end of your URL, and it might get through your form into your query:

#******************************************************************************
# Function: safeSQL()
#   Author: Ron Savage
#     Date: 04/22/2009
# 
# Description:
# This removes update,create,drop,deletes from SQL.
#******************************************************************************
sub safeSQL
   {
   my $cmd;
   my ( $inText,$commandList ) = @_;

   if (!defined($commandList)) { $commandList = "create,delete,select,update,dele,drop,exec,insert"; }

   foreach $cmd (split(/\,/,$commandList))
      {
      $inText =~ s/ $cmd |^$cmd /** no_${cmd}_allowed! **/gi;
      }

   return($inText);
   }
Ron Savage