by Dragos, on October 14th, 2008  
I am currently developing a website that needs a good script to search in the database. The basic MySQL function LIKE doesn't return some good results and because i didn't want to go deeper with mysql with its regex i started to create my own script to search in a mysql database, actually it is a class, my first class ever written :) .
So here it is:
class PHP_MySQL_search {
/*
Copyright 2008 Mocrii Dragos.
To understand how this class works and what you need to do in order to use it, go to http://seoanalytic.com/blog/55/php-mysql-search-class-script/
*/
function setDBdetails($host,$usr,$pwd) { //set database details
$this->HOST=$host;
$this->USR=$usr;
$this->PWD=$pwd;
}

function DBselect($db) { //set database to work with
$this->db=$db;
}
function setTable($table) { //set table(s) to search in
$this->table=$table;
}
function setID($id) { //select the identifier of your rows. Usually it is id
$this->ID=$id;
}
function setColumns($cols) { //set the columns to search in
$this->columns=$cols;
}
function setOrderBy($orderby) { //this is how data will be retrieved from the database. This is not how results will be displayed.
$this->OrderBy=$orderby;
}
function setLimit($num) { //set the limit of results per page
$this->Limit=(int)$num;
}
function setBegin($num) { //set the start row. Starting with this row results will be retrieved until limit has been reached.
$this->BeginFrom=(int)$num;
}
function nin_array($val) { //filter arrays from common words. You may add your own.
$filtered=array('that','with','they','have','this','from','some','what','which','each','then','when','only','because');
return (strlen($val)>3 && !in_array(strtolower($val),$filtered));
}
function find($kp) { //this will search and return the result array
$kp=trim(strip_tags(urldecode($kp)));
$matches=array('\'','"','/','.',',','`','!','?','@','%','_','*','[',']','{','}','$'); //filter from punctuation signs. only plain text is needed
$replacements='';
$kp=str_replace($matches,$replacements,$kp); //This will filter unwanted chars
$kp=preg_replace('/\s\s+/', ' ', $kp); //This will filter excess whitespace
$kpa=explode(' ',$kp);
$kpa=array_filter($kpa,array($this,"nin_array"));
if(!$this->BeginFrom || $this->BeginFrom=='') $this->BeginFrom=0;
if(!$this->Limit || $this->Limit=='') $this->Limit=10;
if(!$this->columns || $this->columns=='') {
$this->columns="*";
$build_query="SELECT ".$this->columns." FROM ".$this->table.($this->OrderBy!=''?" ORDER BY ".$this->OrderBy:"")." LIMIT ".$this->BeginFrom.",18446744073709551615";
}
else {
$build_query="SELECT ".$this->ID.",".$this->columns." FROM ".$this->table.($this->OrderBy!=''?" ORDER BY ".$this->OrderBy:"")." LIMIT ".$this->BeginFrom.",18446744073709551615"; //the big number is used to select all rows from limit to the end of the table. if you have more than 18446744073709551615 rows in your table, change this number to a bigger one :)
}
$con=mysql_connect($this->HOST,$this->USR,$this->PWD);
if(!$con || !mysql_select_db($this->db)) return false;
$my_query=mysql_query($build_query,$con);
//echo mysql_num_rows($my_query);
$results=array(); //echo $build_query;
$kontor=0;
$kontor2=0;
while($row=mysql_fetch_array($my_query,MYSQL_ASSOC)) {
$kontor2++;
$row=array_map('stripslashes',$row);
$tmp=implode(' ',$row);
$matches=array('\'','"','/','.',',','`','!','?','@','%','_','*','[',']','{','}','$');
$replacements='';
$tmp=trim(strip_tags($tmp));
$tmp=str_replace($matches,$replacements,$tmp); //This will filter unwanted chars
$tmp=preg_replace('/\s\s+/', ' ', $tmp); //This will filter excess whitespace
$tmpa=explode(' ',$tmp);
$tmpa=array_filter($tmpa,array($this,"nin_array"));
$tmpa=array_map("strtolower",$tmpa);
for($i=0;$i $found2=false;
foreach($tmpa as $kke) {

foreach($kpa as $kpp) {
if(abs(strlen($kke)-strlen($kpp))<=2 && (substr($kke,0,strlen($kpp))==$kpp || substr($kpp,0,strlen($kke))==$kke)) { $found2=true; $found[$kpp]++; }
}

}

if($found2===true) { $bld=array("kwds"=>$found,"res"=>$row); array_push($results,$bld); $kontor++;}
if($kontor>=$this->Limit) break; //if limit has been reached then break out of the while cycle
}
mysql_close($con);
return $results;
}

}


To use it you need to set some details. Here is an example of its use:

$msearch=new PHP_MySQL_search;
$msearch->setDBdetails("localhost","root","secret_password"); //
$msearch->DBselect("database_name");
$msearch->setTable("table_name(s)");
//$msearch->setOrderBy("id");
$msearch->setID("id");
$msearch->setBegin(0); // this will be used to form the SELECT query: limit 0,2 , for example
$msearch->setLimit(15); //this is the number of the results per page
$msearch->setColumns("title,name,occupation"); //columns to search in. If you do not want to specify the columns then comment this line or set the value *
$result_array= $msearch->find('keyword phrase')
print_r( $result_array );



The dump of $result_array will have the form:
Array ( [0] => Array ( [kwds] => Array ( [keyword1] => 1, [keyword2]=> 5 ) [res] => Array ( [id] => 34 [title] => The title [content] => The content [summary] => This is about ...) ) ) ,
where the main array contains all results, the second one contains the exploded words of the keyword phrase and how many times each one was found + [res] contains an array with the results from the columns you specified, or all columns if you set the * value. If it is hard for you to understand my explanation, i bet it is, just try it yourself and analyze the output for at least 3 different keyword phrases.
Any questions? Ask here.