Implementation code for searching and highlighting keywords within the php site

  • 2020-05-10 17:51:55
  • OfStack

 
<?php 
require_once 'sqlTools.class.php';// Encapsulating class, executable dql , dml statements  
$info=$_POST['info']; 
$sql="select name,password,email from user_500 where name like '%$info%' or password like '%$info%' or email like '%$info%'"; 
$sqlTools=new SqlTools(); 
$res=$sqlTools->execute_dql($sql); 
while ($row=mysql_fetch_assoc($res)){ 
$row['name']=preg_replace("/($info)/i","<b style=\"color:red\">\\1</b>",$row['name']); 
$row['password']=preg_replace("/($info)/i","<b style=\"color:red\">\\1</b>",$row['password']); 
$row['email']=preg_replace("/($info)/i","<b style=\"color:red\">\\1</b>",$row['email']); 
echo $row['name']."-->".$row['password']."-->".$row['email']."<br>"; 
} 
?> 

Thought analysis:
When the %$info% contained in the sql statement is handed over to DBMS for execution, he will look for information about the value of the variable $info in the field.
%$info--- > Find information that ends with a value of $info
$info%--- > Look for information that begins with a value of $info
Highlight the searched keywords through the regular function preg_replace(), for example,
$row [' name] = preg_replace ("/($info)/i "," < b style=\"color:red\" > \\1 < /b > ",$row['name']);
The value $info received through POST is replaced with the result of the plus style (bold in red) and reassigned to $row[' name']
If you want to search for multiple keywords, you can split the received value $info, such as $info_more=explode(" ",$info); // this allows you to segment the keywords separated by Spaces and query the results one by one. Again, you can use the regular expression function to perform the substitution to highlight the keywords
sqlTools.class.php source code:
 
<?php 
class SqlTools{ 
private $host="localhost"; 
private $dbname="test"; 
private $dbuser="root"; 
private $dbpwd=""; 
private $conn; 
public function __construct(){ 
$this->conn=mysql_connect($this->host,$this->dbuser,$this->dbpwd); 
if(!$this->conn){ 
die(" Connection to database failed ".mysql_error()); 
} 
mysql_select_db($this->dbname,$this->conn) or die(" The database could not be found ".mysql_error()); 
mysql_query("set names utf8"); 
} 
public function execute_dml($sql){ 
$bool=mysql_query($sql); 
if ($bool){ 
if ($bool>0) { 
return 1; 
}else{ 
return 2; 
} 
}else { 
return 0; 
} 
} 
public function execute_dql($sql){ 
$res=mysql_query($sql); 
return $res; 
} 
public function close_conn(){ 
mysql_close($this->conn); 
} 
} 
?> 

Original article: WEB development _ xiaofei

Related articles: