If you are a php programmer then this article will very helpful in your career. Highlight your keyword in your searching results which will help your user to identify the more appropriate records. As you know Searching Functionality is very useful feature to find relevant data quickly from the database records. Highlight Keyword feature makes the search functionality more user-friendly.
In Search terms, this feature will give you option to change the keywords background color or text color with different colors in search records. In this tutorials, i will show you how to fetch records from database and highlight keywords in search results using PHP and MySql.
Highlight Keywords in records
The highlight_keywords() is a custom defined function that will use to highlight the words in search results.
2 3 4 5 6 7 8 9 10 11 12 13 14 |
function highlight_keywords($text, $keyword) { $wordsArray = explode(" ", $keyword); $wordsCount = count($wordsArray); for($i=0;$i<$wordsCount;$i++) { $highlighted_text = "<span style='font-weight:bold;background-color: #F9F902;'>$wordsArray[$i]</span>"; $text = str_ireplace($wordsArray[$i], $highlighted_text, $text); } return $text; } |
- The explode() function is used to convert keyword string into array of each word.
- The PHP str_ireplace() function is used to replace and highlight the each matched word .
For this example, First we will create a “posts” table with some fields like id, title, content,created_on in database. This table will holds the multiple records which will be use to search records and highlight searching keywords.
2 3 4 5 6 7 8 9 10 |
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_on` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; |
Database Configuration file (dbConfig.php)
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php // Database configuration $dbHost = "localhost"; // database host $dbUsername = "root"; // database username $dbPassword = ""; // database password $dbName = "tutorialswebsite"; // database name // Create database connection $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); // Check connection if ($db->connect_error) { die("Connection failed: " . $db->connect_error); } ?> |
index.php file with HTML Search form
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<div class="row"> <div class="col-lg-12"> <h2>Search Records</h2> <!-- Search form --> <form method="post" action="search_result.php"> <div class="input-group"> <input type="text" name="keyword" "="" placeholder="Search by keyword..."> <input type="submit" name="searchSubmit" value="Search"> </div> </form> </div> </div> |
HTML Form will help to search keyword string. After submit form the input keyword will pass using post method to search_result.php file.
search_result.php file
In this file, we will receive submit keyword value and search the records from database.
The Where clause is used to filter the records from database using LIKE operator.
Before displaying the search records, the highlight_keywords() function is used to add the highlight inline css in the matched words.
When the keywords are wrapped with highlight the word in the search records, then the attached inline css is used to highlight the string with background color (As per your inline css properties).
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php // Include the database config file require_once 'dbConfig.php'; // If the search form is submitted $searchKeyword = $queryCondition = ''; if(isset($_POST['searchSubmit'])){ $searchKeyword = $_POST['keyword']; if(!empty($searchKeyword)){ $wordsAry = explode(" ", $searchKeyword); $wordsCount = count($wordsAry); $queryCondition = " WHERE "; for($i=0;$i<$wordsCount;$i++) { $queryCondition .= "title LIKE '%" . $wordsAry[$i] . "%' OR content LIKE '%" . $wordsAry[$i] . "%'"; if($i!=$wordsCount-1) { $queryCondition .= " OR "; } } } } // Get matched records from the database $result = $db->query("SELECT * FROM posts $queryCondition ORDER BY id DESC"); // Highlight words in text function highlight_keywords($text, $keyword) { $wordsArray = explode(" ", $keyword); $wordsCount = count($wordsArray); for($i=0;$i<$wordsCount;$i++) { $highlighted_text = "<span style='font-weight:bold;background-color: #F9F902;'>$wordsArray[$i]</span>"; $text = str_ireplace($wordsArray[$i], $highlighted_text, $text); } return $text; } if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $title = !empty($searchKeyword)?highlight_keywords($row['title'], $searchKeyword):$row['title']; $content = !empty($searchKeyword)?highlight_keywords($row['content'], $searchKeyword):$row['content']; ?> <div class="list-item"> <h4><?php echo $title; ?></h4> <p><?php echo $content; ?></p> </div> <?php } }else{ ?> <p>No post(s) found...</p> <?php } ?> |
Highlight Keywords with CSS
You can also use class instead of inline css to highlight keyword in records. In this case, the highlight_keywords() will be modified like the following code:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Highlight words in text function highlight_keywords($text, $keyword) { $wordsArray = explode(" ", $keyword); $wordsCount = count($wordsArray); for($i=0;$i<$wordsCount;$i++) { $highlighted_text = "<span class='highlightword'>$wordsArray[$i]</span>"; $text = str_ireplace($wordsArray[$i], $highlighted_text, $text); } return $text; } |
2 3 4 |
<span class="highlightword">$wordsAry[$i]</span> in this line "highlightword" is custom class name you can change it. |
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co