Generating WHERE clause...php function?

Status
Not open for further replies.
I have created a page that is a custom search page with many fields. First Name, Last Name, City, State, Zip, etc...

What I'm trying to do is create the WHERE clause to pass to the db in a more elegant way. I know I can do IF THEN ELSE to determine if the string is empty but there are a lot of fields and I want to create an elegant way of handling this. Basically I want to avoid having a long block of IF THEN code.

Any ideas on this?

I was thinking about:

1. Store the variables in an array.
2. Iterate through them to see if they're empty or not
3. If not add it to the WHERE clause

The variable names are the same as the db fields so I guess I would just chop of the '$' (PHP) sign that declares the variable to complete the WHERE FirstName LIKE '%FirstName%'.

How does this sound?
 

obrienm

Wise, Aged Ars Veteran
120
Maybe you do something like the following. This isn't tested mind you.

Code:
$searchArray = array();
$firstName = (isset($_REQUEST['firstName'])) ? array_push($searchArray, "firstName = \"".$_REQUEST['firstName']."\") : "";

$clause = implode("AND ", $searchArray);

So you'd basically be pushing your variables into the $searchArray and then joining them all together into a single $clause variable that you can use in your SQL string.
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
Jackass JoeJoe":1sm44s29 said:
dolphyjazz":1sm44s29 said:
How does this sound?

Like a SQL injection just waiting to happen.
This. This this this. Get a database library that is smarter than you are. I use CodeIgniter's (and thus just call $db->where() within a foreach loop), but there are free ones.

If you don't see why this code is apocalyptically bad, you need to not be writing direct database queries.
 
Blacken00100":2639zv7u said:
Jackass JoeJoe":2639zv7u said:
dolphyjazz":2639zv7u said:
How does this sound?

Like a SQL injection just waiting to happen.
This. This this this. Get a database library that is smarter than you are. I use CodeIgniter's (and thus just call $db->where() within a foreach loop), but there are free ones.

If you don't see why this code is apocalyptically bad, you need to not be writing direct database queries.

I will look into this. I'm new to PHP so I appreciate all the help I can get.

Thanks.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
I've pulled this code out of a personal project I was screwing around with. This is not production ready code, probably has issues, etc, etc.

However, it builds simple queries and uses prepared statements. (The second file is an example query).



Code:
Query.class.php
<?php

class Query {
  private $query;
  private $prefixlist;
  private $postfixlist;
  private $table;
  private $alias;
  private $fieldlist;
  private $joins;
  private $parameters;
  private $orderby;
  private $values;
  private $numberOfPages;
   
  function Query($primarytable) {
    
    $this->table = $primarytable;
    $this->alias = $primarytable;
    // SELECT {fieldlist} 
    //   FROM {primarytable}
    //     JOIN 
  }
  
  function SetDisplayList (array $fieldlist) {
    $this->fieldlist = $fieldlist;
  }

  function SetTableAlias($alias) {
    $this->alias = $alias;
  }
  
  function AddJoin ($typeofjoin, $jointable, $joinalias, $criteria) {
    $defcriteria = "{$joinalias}.iCompanyID = {$this->alias}.iCompanyID AND {$joinalias}.iDivisionID = {$this->alias}.iDivisionID";
    
    $newjoin = $typeofjoin.' '.$jointable.' '.$joinalias.' ON ('.$defcriteria;
    if (strlen($criteria) > 0) {
      $newjoin = $newjoin.' AND '.$criteria;
    }
    $newjoin = $newjoin.') ';
    $this->joins[] = $newjoin;
/*
 * 
 * JOIN Site_Page2Site_Section ON (Site_Page2Site_Section.iCompanyID = Site_Page.iCompanyID
                            AND Site_Page2Site_Section.iDivisionID = Site_Page.iDivisionID
                            AND Site_Page2Site_Section.iSite_PageID = Site_Page.iSite_PageID)
JOIN Site_Section ON (Site_Section.iCompanyID = Site_Page2Site_Section.iCompanyID
                  AND Site_Section.iDivisionID = Site_Page2Site_Section.iDivisionID
                  AND Site_Section.iSite_SectionID = Site_Page2Site_Section.iSite_SectionID)
 * 
 */
    
  }
  
  function AddParameter ($criteria1, $value) {
    
    $this->parameters[] = $criteria1;
    $this->values[] = $value;  
    
  }

  function AddPrefixOption ($value) {
    $this->prefix[] = $value;
  }
  
  function AddPostfixOption ($value) {
    $this->prefix[] = $value;
  }
  
  function SetOrderBy ($orderby) {
    $this->orderby = $orderby;
  }
  
  function ExecuteSelectQuery () {
    global $db;
    
      $select = $this->BuildSelectQueryString();
      $select = $db->Prepare($select);
    
    $ret = $db->Execute($select,$this->values);
    return $ret;
  }
  
  function ExecuteQueryWithPaging($ar) {
    global $db;
      $select = $this->BuildSelectQueryString();
      
      $select = $db->Prepare($select);

      if (isset($ar['Page'])) {
        $iPage = (int)$ar['Page'];
        if (isset($ar['PageLength'])) {
          $iPageLength = (int)$ar['PageLength'];
        }
        else {
          $iPageLength = 10;
        }
      } else { 
          $iPage = 1;
          $iPageLength = 10;
      }
      //var_dump("Page:$iPage PageLength:$iPageLength");
      $ret = $db->PageExecute($select, $iPageLength, $iPage, $this->values);
      $this->numberOfPages = ((int)$ret->_maxRecordCount / $iPageLength) + (($ret->_maxRecordCount %  $iPageLength) > 0) ;      
      return $ret;
  }

  function BuildSelectQueryString () {
    global $db;
    $prefixoptions = '';
    if (isset($this->prefixlist)) {
      foreach($this->prefixlist as $prefix) {
        $prefixoptions = $prefixoptions.' '.$prefix;
      }
    }
    
    $postfixoptions = '';
    if (isset($this->postfixlist)) {
      foreach($this->postfixlist as $postfix) {
        $postfixoptions = $postfixoptions.' '.$postfix;
      }
    }
    
    $listoffields = '';
    if (isset($this->fieldlist)) {
      foreach($this->fieldlist as $field) {
        $listoffields = $listoffields.', '.$field;
      }
      $listoffields = ltrim($listoffields,',');
    }
    $select = 'SELECT '.$prefixoptions.' '.$listoffields;
     
    if (strcasecmp($this->table,$this->alias) == 0)
      $from = ' FROM '.$this->table;
    else
      $from = ' FROM '.$this->table.' '.$this->alias;
      
    $joinlist = '';
    if (isset($this->joins)) {
      $joinlist = '';
      foreach($this->joins as $j) {
        $joinlist = $joinlist.$j; 
      }
    }
    $where = '';
    $parmlist = '';
    if (isset($this->parameters)) {
    $where = ' WHERE ';
      foreach($this->parameters as $p) {
        if ( strlen($parmlist) > 0 ) {
        $parmlist = $parmlist.' AND '.$p;
        } else {
          $parmlist = $p;
        }
      }
    }
    $orderby = '';
    if (isset($this->orderby)) {
      $orderby = ' ORDER BY '.$this->orderby;
    }
    
  //  $parmlist = '';
    $where = $where.$parmlist;
    
    $select = $select.' '.$from.' '.$joinlist.' '.$where.' '.$orderby.' '.$postfixoptions;

    //var_dump($select);
    
    //var_dump($this->values);
    
    return $select;
  }
  
  function getNumberOfPages () {
    return $this->numberOfPages;
  }
  
  // AddParameter
  // - select clause
  // SELECT {table1}.{fieldname1}, [table1}.{fieldname2}, {table2}.{fieldname3}
  //   FROM {table1}
  //   WHERE 
  //   INNER JOIN/OUTER JOIN (...)
  // 
  // SELECT [ ALL | DISTINCT ]
  //  [ TOP n | TOP n PERCENT | TOP n WITH TIES | TOP n PERCENT WITH TIES ]
  // { [ table_name. | table_alias. | view_name. ]
  //   { * | column_name [[ AS ] column_alias ] | expression [[ AS ] column_alias | IDENTITYCOL [[ AS ] column_alias 
  //       ROWGUIDCOL [[ AS ] column_alias | column_alias = expression
  //   }
  // }
  // [ ..., n ]
  // [ INTO new_table ]
  // [ FROM 
  //   { 
  //     derived_table | AS table_alas  ]
  // [ ... JOIN ... ]
  // [ WHERE ... ]
  // [ GROUP BY ... ]
  // [ HAVING ... ] 
  // [ UNION ... ]
  // [ ORDER BY ... ]
  // [ COMPUTE ... ]
  // [ FOR BROWSE ... ]
  // [ OPTION ... ]
  
}
?>

Code:
<?php

  class UserTable extends TableObject {
    private $tablename = 'User';
    function UserTable () {
      // Init
    }
    
    function FetchBy(array $ar) {
      global $db;

      
      $q = new Query($this->tablename);
      $q->SetDisplayList(array('User.*'));
      
      if (isset($ar['UserID']) ) {
        $q->AddParameter('cUserName = ?', $ar['UserID']);
      }
      if (isset($ar['Password']) ) {
        $q->AddParameter('cPassword = ?', $ar['Password']);
      }

      $rs = $q->ExecuteSelectQuery();      
      return $rs;
    }
  }
?>
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
topham: That looks fairly good and fairly flexible, I don't see any huge obvious issues with it.

Something to look at is the (misnamed) Active Record class in CodeIgniter. It programmatically builds these queries without you having to do a whole hell of a lot, and does so in a way that's similar to how you'd write SQL statements via PDO or something else, but includes special-case code for a bunch of different databases. The Database code is not too tied to CodeIgniter, so it could be pulled out for non-CI projects. Like, for the original issue (lots of WHERE statements), I'd just have code like this:

Code:
foreach ($someArray as $key => $value) {
    if ($value == null) continue;
    $db->where($key, $value);
}
$query = $db->get("tablename");

foreach ($query->row_array() as $row) {
    echo $row['id'];
}

And done.

Hrm...maybe extracting that code will be a quickie project this week.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
newwb":5ebgdapn said:
Blacken00100":5ebgdapn said:
Little Bobby Tables says "bitch, what?". ;)
Little Bobby Tables should have read my whole post. :)

I initially read it the same way he did, there is a conflict between your first and second sentence. I wouldn't consider prepared statements direct queries. (direct queries, prepared statements, object interface).
 
topham":2ix5w4xt said:
I initially read it the same way he did, there is a conflict between your first and second sentence. I wouldn't consider prepared statements direct queries. (direct queries, prepared statements, object interface).
By direct queries, I meant creating the SQL yourself (not including parameter values) instead of letting some sort of SQL abstraction layer build it. Sorry for the confusion.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
dolphyjazz":3baqurj7 said:
Jackass JoeJoe":3baqurj7 said:
dolphyjazz":3baqurj7 said:
How does this sound?

Like a SQL injection just waiting to happen.

Ha! That's hilarious! I will use the mysql_escape_string function before sending it to the db.

mysql_escape_string should never be used.
However, it should always be used if you aren't using prepared statements.
However, you should never not use prepared statements.

Use prepared statements.
Use a library that uses prepared statements.

or, if you absolutely must; use a library that uses mysql_escape_string as necessary and that doesn't put the requirement back on you in your code.

However, never use mysql_escape_string or code that uses it.
 
Status
Not open for further replies.