Search functionality is very useful for the data list. It helps to find the relevant records quickly from the database. Search term highlighting feature makes the search functionality user-friendly. Highlight keyword helps the user to easily identify the more relevant records in search results.
In the keywords highlighting feature, the search terms are highlighted with the different background color or text color in the search results. In this tutorial, we will show you how to search in MySQL database and highlight keyword in search results with PHP.
The highlightWords() is a custom function that helps to highlight the words in the text.
$text
– The content to search and replace.$word
– The string to search for.// Highlight words in text function highlightWords($text, $word){ $text = preg_replace('#'. preg_quote($word) .'#i', '<span class="hlw">\\0</span>', $text); return $text; }
In the example code, we will fetch the posts data from the database and listed on the web page. Based on the search, the records will be filtered and the search term will be highlighted in the search results.
For this example, we will create a posts table with some basic fields in the MySQL database. The posts
table holds the records which will be searched and highlighted.
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following code is used to connect the database using PHP and MySQL. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your database credentials.
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "codexworld"; // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); }
Initially, all the records are fetched from the database and listed on the web page. Based on the search keyword, the words are highlighted in the search list.
highlightWords()
function is used to add the highlighting class in the matched words.<?php // Include the database config file require_once 'dbConfig.php'; // If the 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 content 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; } ?>
<!-- Search form -->
<form method="post">
<div class="input-group">
<input type="text" name="keyword" value="<?php echo $searchKeyword; ?>" placeholder="Search by keyword..." >
<input type="submit" name="searchSubmit" value="Search">
</div>
</form>
<!-- Search results -->
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$title = !empty($searchKeyword)?highlightWords($row['title'], $searchKeyword):$row['title'];
$contnet = !empty($searchKeyword)?highlightWords($row['content'], $searchKeyword):$row['content'];
?>
<div class="list-item">
<h4><?php echo $title; ?></h4>
<p><?php echo $contnet; ?></p>
</div>
<?php } }else{ ?>
<p>No post(s) found...</p>
<?php } ?>
You can use inline CSS to highlight the words in the text without using a CSS class. In this case, the highlightWords() will be modified like the following.
function highlightWords($text, $word){ $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text); return $text; }
PHP CRUD Operations with Search and Pagination
Our highlightWords() class will work the both text and HTML content. Using the example code, you can highlight keywords in the search results with HTML content. This search highlight functionality will be very useful for the list of the data management section. Also, you can easily enhance our highlight search keyword functionality using PHP and MySQL.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
This is very cool and I implemented it in seconds, works a dream!! Thank you very much. However I do not understand the regular expression syntax behind the functionality. I have tried looking up various regular expression queries but as yet have not found reference to ‘#’. What magic is behind this!!??
Really simply and effective code, great tip. Thank you.
It is an amazing post and you explained in a detailed way. Nice to see this here. I will bookmark your blog for more details. Keep sharing the new things like this.
How to do this in prepared statement?