Dynamic SQL query on multiple fileds

This is one way of creating dynamic SQL queries based on a POST array of fields. In this version it's possible to configure one field to search in multiple database tables.

<?php
   
public function searchCustomer($_POST) {
       
       
// sanitize the values from bad characters
       
foreach ($_POST as $key => $value) {
           
$post[$key] = filter_var($value, FILTER_SANITIZE_STRING);
        }
       
/*  $_POST array
        [txtCompanyID] => 12345
        [txtCompanyName] => Company AB
        [txtReferenceName] => Nilsson
        [txtPhone] => 013-123456
        [txtAddress] => Astreet 123
        [txtPostaddress] => 123 45 City
        [txtCountry] => Sweden
         */
       
        // unset values from form items not desired
       
unset($post['subSearch']);
       
      
// configure what fields to match in the database table
       
$match = array('txtCompanyID' => 'CompanyID',
                      
'txtCompanyName' => 'CompanyName',
                      
'txtReferenceName' => 'ReferenceName',
                      
'txtPhone' => array('Phone', 'Mobile'),
                      
'txtAddress' => 'Address',
                      
'txtPostaddress' => 'Postaddress',
                      
'txtCountry' => 'Country',
                      );
       
       
// loop all posted values
       
foreach ($post as $key => $value) {
           
            if(!empty(
$value)){
               
$fields = $match[$key];
                if(
is_string($fields)){
                   
$where[] = $match[$key]. " LIKE '%" . $value . "%'";
                }else{
                   
                    foreach (
$match[$key] as $k => $tbl) {
                       
$where_tmp[] = $tbl. " LIKE '%" . $value . "%'";
                    }
                   
$where[] = " (".implode(" OR ", $where_tmp).") ";
                    unset(
$where_tmp);
                }
            }         
        }
       
      
$where_sql = implode(" AND ", $where);
        ....

      
// The variable  $where_sql will contain:
       //  CompanyID LIKE '%12345%' AND CompanyName LIKE '%Company AB%' AND ReferenceName LIKE '%Nilsson%' AND (Phone LIKE '%013-123456%' OR Mobile LIKE '%013-123456%') AND Address LIKE '%Astreet 123%' AND Postaddress LIKE '%123 45 City%' AND Country LIKE '%Sweden%'
       
   
}
?>
Knowledge keywords: