<?php Class Search extends scurd{ /* constructor, initializing the connection, using the same method as the parent class * * function __construct ($HOST, $DB _user, $PASSWD, $DB) { Parent::__construct ($HOST, $DB _user, $PASSWD, $DB); } /* destructor, close connection * * function __destruct () { Parent::__destruct (); } /** * Public method, search string and highlight text, return a two-dimensional array result set * @parameter $table (type of string, required), fill in the table of the required query * @parameter $fieldName (type of string, required), fill in the name of the field you want to search * @parameter $strSearch (String type, required), fill in the required search string * @parameter $hlColor (type of string, optional), fill in the color of the highlighted text, the default is red **/ function ISearch ($table, $fieldName, $strSearch, $hlColor = ' red ') { $arrSearch = Explode (", $strSearch); foreach ($arrSearch as $value) { $conditions [] = "$fieldName like '% $value% '"; } $condition = Is_array ($conditions)? Implode (' OR ', $conditions): $conditons [0]; $ARRSTR = Parent::r ($table, Array (' * '), $condition); if ($ARRSTR) { for ($i = 0; $i < count ($arrStr); $i + +) { foreach ($arrSearch as $key => $sValue) { $ARRSTR [$i] [$fieldName] = $this->hlstr ($arrSearch [$key], $arrStr [$i] [$fieldName], $hlColor); } } } return $arrStr; } /** * Private method, highlighted text, returns the highlighted string * @parameter $needle (type of string, required), fill in the string you want to find * @parameter $haystack (String type, required), fill in the searched string * @parameter $color (String type, required), fill in the color of the highlighted text **/ Private Function Hlstr ($needle, $haystack, $color) { $str = Str_ireplace ("$needle", "<font style= ' color: $color; ' > $needle </font> ", $haystack); return $str; } }
Using the sample if (Isset ($_get[' Txtsearch ')) {//To determine whether the form is submitted $str = $_get[' Txtsearch ']; The search string assignment to $str $s = new search (' localhost ', ' root ', ' ", ' test '); Instantiate a search class $results = $s->isearch (' test ', ' message ', $STR); Assign the result set to $results if ($results) {//To determine whether the result set is empty foreach ($results as $key => $value) {//Traverse result set Echo ' first '. ($key + 1). ' Record:<br> '; Echo ' ID: '. $value [' id ']. ' ' . ' Name: '. $value [' name ']; Echo ' <br> message:<br> '. $value [' message ']. ' <p> '; } } else{ Echo ' no record '; } } ?> <!--write a form submit to this page--> <form action= "" method= "get" > <input name= "Txtsearch" type= "text"/> <input name= "btnsearch" type= "submit" value= "Search"/> </form> For dynamic pages |