How to search using PHP and MySQL

php script to search your site with data from the database. Search by keywords.

How to search using PHP and MySQL
How to search using PHP and MySQL

Below is the php code that searches for several words in one request. This script splits the query into separate words and displays articles from your database in the form of a list with options that match the words in the search query.

DB = 

id | title | description | 

$connect = mysqli_connect('host', 'user', 'pass', 'tab');
//$query = mysqli_query($connect, "SELECT * FROM posts");
//while($row = mysqli_fetch_assoc($query)) echo "<h1>".$row['title']."</h1><p>".$row['description']."</p><br>";


<!DOCTYPE html>
<html lang="en">
 <title>test search</title>

<form method="post">
<input type="text" name="search" >
<input type="submit" name="submit" value="search">
	 $search = explode(" ", $_POST['search']);
	 $count = count($search);
	 $array = array();
     $i = 0;
	 foreach($search as $key){
		 if($i < $count) $array[] = "CONCAT (`title`, `description`) LIKE '%".$key."%' OR "; else $array[] = "CONCAT (`title`, `description`) LIKE '%".$key."%'";
	 $sql = "SELECT * FROM `posts` WHERE ".implode("", $array);
	 //echo $sql;
	 $query = mysqli_query($connect, $sql);
	 while($row = mysqli_fetch_assoc($query)) echo "<h1>".$row['title']."</h1><p>".$row['description']."</p><br>";
	/* $query = mysqli_query($connect, "SELECT * FROM `posts` WHERE `title` LIKE '%$search%' OR `description` LIKE '%$search%' ");
	 while($row = mysqli_fetch_assoc($query)) echo "<h1>".$row['title']."</h1><p>".$row['description']."</p><br>";



on the site are taken from open sources. The site does not contain files for download. All links to files from open sources. Owners of copyrights to the material may request removal of the post from the site.

Become a Patron!