search in php

## Here multiple word search is tried.. Its working..
$data = array();
$data['search_list'] = "";
$data['total_search'] = "";
$data['search_on'] = "";
$data['search_words'] = "";
$_searchfield = "";
$total_search = 0;
$__prepositionArray = array('a','an','the','or','and');
if (isset($_REQUEST['search'])) 
{
 $_searchfield = $_REQUEST['search'];
 $_searchfield = str_replace("'", "", $_searchfield);
 
 //--------Remove extra words--------
 $_searchfield = trim($_searchfield);
 $__prepositionArray = array(' a ',' an ',' the ',' or ',' and ');
 $__prepositionArray2 = array('a','an','the','or','and');
 $__tempString = str_replace($__prepositionArray, " ", $_searchfield);
 $__exactString = preg_replace('/\s+/', ' ',$__tempString);
 $_searchfield = $__exactString;
 
 if(!empty($_searchfield))
 { 
 $searchWords = explode(' ',$_searchfield);
 $searchTermBits = array();
 foreach ($searchWords as $term)
 {
 $term = trim($term);
 if (!empty($term))
 {
 $searchTermBits[] = "p_title LIKE '%$term%'";
 }
 }

 $__multiWordQ = "";
 $__singleWordQu ="";
 $__multiWordQ.= implode(" AND ", $searchTermBits);
 $__singleWordQu = implode(" OR ", $searchTermBits);

 $newQuery = "SELECT * FROM product WHERE active=1 AND p_title like '%$_searchfield%'
 UNION
 SELECT * FROM product WHERE active=1 AND (".$__multiWordQ.")"
 ."UNION 
 SELECT * FROM product WHERE active=1 AND (".$__singleWordQu.")"
 ."UNION 
 SELECT * FROM product WHERE active=1 AND p_kword like '%$_searchfield%'
 UNION 
 SELECT * FROM product WHERE active=1 AND p_desc like '%$_searchfield%'";

 $query = $this->db->query($newQuery);
 $total_search = $query->num_rows();
 $data['search_list'] = $query->result_array();
 $data['total_search'] = $total_search;
 $data['search_on'] = $_REQUEST['search'];
 $data['search_words'] = $searchWords;
 }
}
Please follow and like us: