In this post, we will show you how to highlight matched words in Search Results with PHP and MySQL With an Example and Demo. Welcome to CodeAT21.com – We are providing full source code via GitHub and live demo via youtube.
In the PHP code using Highlight Keywords in your searching results in the user to identify the more right records fetch from MySQL database. This PHP code is searching multiple keywords highlighting search results. In this Highlight Keywords code title and description fetch from MySQL database. This is a simple PHP code you can easily customize or just copy and paste code according to our requirements.
Create Database Table
So first, create a database name called codeat21_keywords into your MySQL database. And after that, Our MySQL table name called search_post and has three columns only – id, title, and description.
- MySQL Database Name – codeat21
- MySQL Table Name – posts
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` LONGTEXT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Connection using PHP
After creating the codeat21 MySQL Database. And in this tutorial, We will write the PHP code to connect the Database using PHP and MySQL.
Database Information
- The Host of the Database – “localhost”
- The user of the Database – “root”
- The password of the Database – “” (By default, the password is empty.)
- Name of the Database – “codeat21”
dbConfig.php<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = ""; $dbName = "codeat21"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } ?>
Searching and Highlighting Matched Keywords
This PHP code will work the search keywords in the title or description.
First, A search input to enter few keywords and check to the database if any one of the entered search keywords is found. after that our highlightWords() class in the matched words will work.
index.php<?php // Include database config file require_once 'dbConfig.php'; // If search form is submitted $searchKeyword = $whrSQL = ''; if(isset($_POST['searchSubmit'])){ $searchKeyword = $_POST['keyword']; if(!empty($searchKeyword)){ // SQL query to filter records based on the search term $whrSQL = "WHERE (title LIKE '%".$searchKeyword."%' OR description LIKE '%".$searchKeyword."%')"; } } // Get matched records from the database $result = $db->query("SELECT * FROM posts $whrSQL ORDER BY id DESC"); // Highlight words in text function highlightWords($text, $word){ $text = preg_replace('#'. preg_quote($word) .'#i', '<span class="hlw">\\0</span>', $text); return $text; } ?> <!DOCTYPE html> <html lang="en-US"> <head> <title> Codeat21 - PHP Highlight Keywords in Search Results with MySQL </title> <meta charset="utf-8"> <!-- Stylesheet file --> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <div class="row"> <h2>Posts List (<?php echo $result->num_rows; ?>) </h2> <!-- Search form --> <form method="post"> <div class="input-group"> <input type="text" name="keyword" class="form-control" value="<?php echo $searchKeyword; ?>" placeholder="Search by keyword..." > <div class="input-group-append"> <input type="submit" name="searchSubmit" class="btn btn-outline-secondary btn-colors" value="Search"> <a href="index.php" class="btn btn-outline-secondary btn-colors2">Reset</a> </div> </div> </form> <!-- Search results --> <?php if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $title = !empty($searchKeyword)?highlightWords($row['title'], $searchKeyword):$row['title']; $description = !empty($searchKeyword)?highlightWords($row['description'], $searchKeyword):$row['description']; ?> <div class="list-item"> <h4><?php echo $title; ?></h4> <p><?php echo $description; ?></p> </div> <?php } }else{ ?> <div class="list-item"> <p>No post(s) found...</p> </div> <?php } ?> </div> </div> </body> </html>
Conclusion
That’s all, this post is how to Highlight matched Words in Search Results using PHP and MySQL. In this post, we learned PHP highlighting multiple keywords in search results with MySQL. You can download the above code and customize this code for your requirement.
This Article full source file in our Github repository. https://github.com/CodeAT21 – This link is a CodeAT21 Github repository.