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>";



Our website is for sale! The domain and website has been running for more than 3 years, but it's time to part with it. There is no price, so I consider any offer. Contact us if you are interested in buying in the feedback form, we will discuss options, price and details for transferring the site. (script, database and everything else for the site to work).