AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Highlight Keyword in Search Results with PHP and MySQL     

Highlight Keyword in Search Results with PHP and MySQL     

Lakshika Mathur by Lakshika Mathur
December 27, 2019
Reading Time: 4 mins read
0
Highlight Keyword in Search Results with PHP and MySQL     

Search functionality is beneficial for the data list. It helps to find the related records rapidly from the database. The search term highlighting feature makes the search functionality user-friendly. Highlight keyword helps the user to identify the more pertinent records of search results quickly.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

In the search Highlight keyword feature, search terms are highlighted in search results with different background colours or text colours. In this tutorial, we will explain to you how to search in the MySQL database and highlight keywords in search results with PHP.

Highlight Words in Text          

It is a custom function. Therefore, it will help to highlight the words in the text.

  • You can use the PHP preg_replace() function to perform a regular expression search and add an element to each matched string.
  • A class attribute is attached to the element. So, you can use it to specify the highlight colour with CSS.
  • The highlightWords() function accepts two parameters,
    • $text – To replace and search.
    • $word – The string to search.
// 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 sample code script, we will fetch the posts data from the database and listed on the web page. Therefore, the records will be filtered that are based on a search result, and it will highlight the search term in the search results.

Create Database Table

For this instance, we will make a posts table with some necessary fields in the MySQL database. The posts table holds records that can 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;

Database Configuration (dbConfig.php)

You can use the following code 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     = "allsweb";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

SEE ALSO: Live Image Upload, Crop and Resize using jQuery and PHP

Highlight Keywords in Search Results    

At first, it will fetch all the records from the database and list them on the web page. According to your most searched keyword, the words are highlighted in the search list.

  • An HTML form is provided to filter the records based on the keywords.
  • When the user search records by the keyword,
    • The WHERE clause is used with the LIKE operator to filter the documents by search term.
    • Before displaying the search results, You can use the highlightWords() function to add the highlighting class in the matched words.
  • Once you wrap the keywords with the highlighting element in the search result, the attached class is used to highlight the string with CSS.
<?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 } ?>

SEE ALSO: Create PDF with Watermark in PHP using Dompdf

Highlight Keywords without CSS

Use inline CSS to highlight the words in the text without using a CSS class. Therefore, it will modify the highlightWords() like the following.

function highlightWords($text, $word){
    $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text);
    return $text;
}

Conclusion          

Firstly, our HighlightScript () class will work on both text and HTML content. Secondly, using ou sample code, you can easily highlight keywords in search results with HTML content. Thirdly, this search highlight functionality would be beneficial for the data management section list. Also, you can quickly develop our highlighted search keyword functionality using PHP and MySQL.

Also, read our previous blog- Import and Export CSV File using PHP and MySQL

Tags: Highlight KeywordPHP and MySQL
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
Add WYSIWYG HTML Editor to Textarea with CKEditor

Add WYSIWYG HTML Editor to Textarea with CKEditor

Auto Resize Textarea Height using jQuery

Auto Resize Textarea Height using jQuery

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version