[eluser]megabyte[/eluser]
I'm working on a search class. I'm not boasting to be a professional here, but I thought I'd post what I have so far and maybe those interested could add or change it and we could develop it into something worthy of a library.
Code:
<?php
class Search extends Controller {
var $tbl = '';
var $temp_tbl = '';
var $fields = '';
function Search()
{
parent::Controller();
}
function index()
{
$data['results'] = $this->get_results($this->input->post('keywords'));
$this->load->view('search', $data);
}
function get_results($keywords){
$keywords = trim($keywords);
if($keywords != ''){
$this->load->database();
$this->load->library('table');
$tmpl = array ('table_open' => '<table border="1" cellpadding="4" cellspacing="0">');
$this->table->set_template($tmpl);
$this->table->set_empty(" ");
$this->tbl = "products";
$this->temp_tbl = "myTempTable";
//split keywords into 2 arrays one for short words and one for long
$long_words = array();
$short_words = array();
$keywords = explode(' ', $keywords);
foreach($keywords as $key =>$val){
if (strlen($val) < 4){
$short_words[] = $val;
}
else{
$long_words[] = $val;
}
}
// create the empty temporary table.
$query = $this->db->query("drop table if exists $this->temp_tbl");
$query = $this->db->query("CREATE TEMPORARY TABLE IF NOT EXISTS $this->temp_tbl like $this->tbl");
// create the query for the long words
if(count($long_words) != 0){
foreach($long_words as $k =>$v){
$query = $this->db->query("INSERT IGNORE INTO $this->temp_tbl (SELECT * FROM $this->tbl WHERE MATCH (style) AGAINST('$v'))");
}
}
if(count($short_words) != 0){
$sql = "INSERT IGNORE INTO $this->temp_tbl SELECT * FROM $this->tbl";
foreach($short_words as $l => $m){
if($l == 0){
$sql .= " WHERE style LIKE '%".$m."%'";
}
else{
$sql .= " OR style LIKE '%".$m."%'";
}
}
$query = $this->db->query($sql);
}
$query = $this->db->query("Select DISTINCT COUNT(*) as occurences, id, style from $this->temp_tbl Group By id ORDER BY occurences DESC");
//$query = $this->db->get('TPHS', 200, '');
if ($query->num_rows() > 0)
{
$data['found'] = 'Results Found:'.$query->num_rows();
$data['rows'] = $this->table->generate($query);
return $data;
}
}
}
}
?>