article

Saturday, December 14, 2019

Highlight Keyword in Search Results with PHP and MySQLi

Highlight Keyword in Search Results with PHP and MySQLi
<!DOCTYPE html>
<html>
<head>
 <title>Highlight Keyword in Search Results with PHP and MySQLi</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName     = "test";

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

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

// 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 (Country LIKE '%".$searchKeyword."%' OR CountryAbbrev LIKE '%".$searchKeyword."%')";
    }
}

// Get matched records from the database
$result = $db->query("SELECT * FROM countries $whrSQL ORDER BY ID ASC");

// Highlight words in text
function highlightWords($text, $word){
    $text = preg_replace('#'. preg_quote($word) .'#i', '<span style="background-color: #F9F902;">\\0</span>', $text);
    return $text;
}
?>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
   <h2>List of Countries</h2>
   <!-- Search form -->
   <form method="post">
    <div class="col-lg-6">
     <input type="text" name="keyword" class="form-control" value="<?php echo $searchKeyword; ?>" placeholder="Search by keyword..." >
    </div> 
    <div class="col-lg-6">
     <input type="submit" name="searchSubmit" value="Search" class="btn btn-success">
    </div>
   </form>
   <br/><br/>
   <!-- Search results -->
   <?php
   if($result->num_rows > 0){
    while($row = $result->fetch_assoc()){
     $title = !empty($searchKeyword)?highlightWords($row['Country'], $searchKeyword):$row['Country'];
     $contnet = !empty($searchKeyword)?highlightWords($row['CountryAbbrev'], $searchKeyword):$row['CountryAbbrev'];
   ?>
   <div class="list-item">
    <h4><?php echo $title; ?></h4>
    <p><?php echo $contnet; ?></p>
   </div>
   <?php } }else{ ?>
   <p>No countries found...</p>
   <?php } ?>
  </div>
    </div>
</div>
<style>
.list-item {
    border-bottom: 2px solid #BABABA;
}
</style>
</body>
</html>

Related Post