Searching Values in a List

5 posts by 2 authors in: Forums > CMS Builder
Last Post: January 14, 2013   (RSS)

Hello, All -

I'm trying to figure out how to run a particular type of search. For a normal search the code would be something like this...


 $search_string = @$_REQUEST['q'];
   
if ($search_string) {     
  $fieldsToSearch = array(     
    'title',     
    'description',
    'etc',
    );  
  $searchClauses = array();     
  foreach ($fieldsToSearch as $field) {       
    array_push($searchClauses, "$field LIKE '%" . mysql_escape($search_string) . "%'");     
  }     
  $where = join(' OR ', $searchClauses);   }
 
  list($searchRecords, $searchDetails) = getRecords(array(     
  'tableName' => 'records',     
  'where'     => $where,
  'perPage'   => '20',


  In the search above, the $fieldsToSearch are textfields or textboxes.
 
  In my particular scenario I need to search a field which is generated by a drop-down list. Only one option can be set - so the value assigned to the $searchClauses will be a single integer.

  The search needs to match than number.

  What do I need to change in the code above to make it work?

:o/

Perchpole

Hi, Jerry -

Thanks for this. However, I really need to crack the piece of code I posted at the top - if only so I learn a bit more!

As I said, I want to match a number in the search. However, the current $where clause doesn't work properly.

This is the normal code:

foreach ($fieldsToSearch as $field) {       
        array_push($searchClauses, "$field LIKE '%" . mysql_escape($search_string) . "%'");     
      }     
      $where = join(' OR ', $searchClauses);   }

However, this will not work when trying to match on a single number as a search for  "2" will match 12,  20, 102, etc....

:0/

Perch

Fixed it.

I needed to change this...

foreach ($fieldsToSearch as $field) {       
        array_push($searchClauses, "$field LIKE '%" . mysql_escape($search_string) . "%'");     
      }     
      $where = join(' OR ', $searchClauses);   } 

to this...

foreach ($fieldsToSearch as $field) {       
        array_push($searchClauses, "$field IN ('" . mysql_escape($search_string) . "')");    
      }     
      $where = join(' OR ', $searchClauses);   } 

There are a number of subtle changes to the apostrophes and quotes wrapped around $search_string that made all the difference!

:0)

Perch

Good Job

Jerry Kornbluth

The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php