Search is an important functionality in an eCommerce website. The world’s best eCommerce websites like Amazon, Alibaba have a fantastic eCommerce live search bar.
Live search helps look around eCommerce website’s sellable entities and their categories. It lets the customers narrow down the results from voluminous information.
We have seen so many examples for enabling the search option in a PHP website. For example, the advanced search in PHP gives a Gmail-like search outlook.
In this article, we will see an example of an Amazon-like eCommerce live search that will be useful for an eCommerce website.
Having a search feature is one of the top 5 best practices of an eCommerce website.
The eCommerce website’s live search functionality varies mainly based on the search criteria. Rarely, it will differ based on the eCommerce entities on which the search filter is going to be applied.
Some of those variations are listed below.
In this tutorial, we will see the live search on the products and categories of an eCommerce website. We have already seen how to do eCommerce product category subcategory search in PHP.
This example code is for implementing live search in an eCommerce website. The live search filter is applied to the products and categories.
The UI lets the users enter the live search keyword. Then the user will see the filtered result on a custom slide-down list. It uses jQuery AJAX to get the live search results.
The live search results are dynamic. It shows the products, categories and the featured items. And, they are from the database. The eCommerce product has the column to be marked as ‘1’ to set as featured.
This code has the configuration to set the maximum number of live search results displayed on the screen.
The PHP AJAX endpoint and the model classes will involve in the live search process flow. The PHP model handlers instantiates the database and prepare select queries. It sets the parameters to fetch the dynamic data.
The below image shows the files created for this eCommerce live search example.
It has the application config with a basic directive to configure the search results count to the UI.
It uses no library for implementing the eCommerce live search. It uses, only the jQuery library as shown in the vendor directory in the below image. Plain, simple and light-weight.
The PHP model Product.php defines functions to get the live search result array from the database.
It has CSS to create a good-looking sliding search results view on typing the keyword in the search box.
It includes the eCommerce product and category images in the image folder of the application root. The search results show products and the category with these images. It will give an enriched UI output to the user.
A database script added to the download is having the statements set up the database to run this example.
The live search is for the category and product database to filter the results based on the keyword. So, the data dump added to this script helps to start filtering and see the live search results.
sql/database.sql
--
-- Database: `live-search`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_category`
--
CREATE TABLE `tbl_category` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`image` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tbl_category`
--
INSERT INTO `tbl_category` (`id`, `name`, `slug`, `image`) VALUES
(1, 'Luxury Ultra thin Wrist Watch', 'Luxury Ultra thin Wrist Watch-1', 'image/watch.jpg'),
(2, 'Luxury XP 1155 Intel Core Laptop', 'XP 1155 Intel Core Laptop-2', 'image/laptop.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `tbl_product`
--
CREATE TABLE `tbl_product` (
`id` int(11) NOT NULL,
`product_code` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`image` text NOT NULL,
`category_id` int(11) NOT NULL,
`featured` varchar(255) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tbl_product`
--
INSERT INTO `tbl_product` (`id`, `product_code`, `name`, `slug`, `description`, `image`, `category_id`, `featured`, `create_at`) VALUES
(1, '3DcAM01', 'FinePix Pro2 3D Camera', 'FinePix Pro2 3D Camera-1', 'Unlimited 4K print quality photography', 'image/camera.jpg', 1, '1', '2021-05-06 05:24:27'),
(2, 'USB02', 'EXP Portable Hard Drive', 'EXP Portable Hard Drive-2', 'A hard drive is a storage device required to hold on to your files and data for the long term', 'image/external-hard-drive.jpg', 2, '1', '2021-05-06 05:27:29');
--
-- Indexes for table `tbl_category`
--
ALTER TABLE `tbl_category`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for table `tbl_category`
--
ALTER TABLE `tbl_category`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
There are some key points for designing a search control for a website. This HTML code is to display the eCommerce live search to browse the products and categories.
Initially, it will display a live search input to the user to enter the keyword. On typing the keyword, it sends the param to the PHP and gets the live search results.
The results are from the database and displayed in a form of a list sliding down from the search box.
Currently, the eCommerce live search result items are not having navigation links. But, the database has a column to store the product and the category slug. It may help to create the permalink for navigation.
It includes the JavaScript file that contains the AJAX method to send the request to PHP to search.
index.php
<html>
<head>
<TITLE>eCommerce Live Search</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
<script src="" type="text/javascript"></script>
</head>
<body>
<div class="phppot-container">
<div class="header-search">
<input type="text" class="img-url" id="search-box"
placeholder="Search for products, categories..." />
<div id="suggesstion-box"></div>
</div>
</div>
<script type="text/javascript" src="vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="assets/js/search.js"></script>
</body>
</html>
And the CSS is,
.phppot-container {
-webkit-font-smoothing: antialiased;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
font-size: .9em;
color: #1e2a28;
width: 740px;
margin: 0 auto;
padding: 0px 20px 20px 20px;
}
.header-search {
padding: 40px;
max-width: 500px;
margin: 0 auto;
}
#search-list {
max-width: 500px;
border-bottom: #E0E0E0 1px solid;
border-left: #E0E0E0 1px solid;
border-right: #E0E0E0 1px solid;
}
#search-box {
padding: 20px;
border: #E0E0E0 1px solid;
border-radius: 0px;
width: 100%;
}
.search-section {
padding: 10px;
border-bottom: 1px solid #E0E0E0;
}
.product-row {
padding: 10px 0px;
clear: both;
}
.description {
line-height: 20px;
display: inline-block;
}
.image-search-result {
height: 36px;
width: 36px;
padding: 0px 0px 0px 0px;
cursor: pointer;
border: #E0E0E0 1px solid;
border-radius: 20px;
margin-right: 10px;
}
.category .image-search-result {
float: none;
vertical-align: middle;
}
.img-url {
background: url("./../../image/demo-search-icon.png") no-repeat center
right 7px;
}
The AJAX script is called on the key-up event of the live search box.
It passes the keyword parameter to the PHP endpoint URL calling from the AJAX.
On completing the request-response flow, it gets the response HTML from the server-side.
In the previous section, we have seen the UI code which has the target container. This is the target to load the dynamic live-search HTML response data.
assests/js/search.js
$(document).ready(function() {
$("#search-box").keyup(function() {
$(".img-url").show();
$.ajax({
type : "POST",
url : "ajax-endpoint/get-search-result.php",
data : 'keyword=' + $(this).val(),
success : function(data) {
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background", "#FFF");
}
});
});
});
There are 4 files involving in the server-side eCommerce live search process.
First, the get-search-result.php is the endpoint file that receives the AJAX request. It reads the live search result and prepares the response HTML with the dynamic data.
It imports the Config.php and Product.php to prepare the database query and the live search request.
It instantiates the DataSource to connect and read the filtered eCommerce entities. The DataSource is a routine class used in many of our example codes.
The following code shows these files one by one as below.
ajax-endpoint/get-search-result.php
<?php
use Phppot\Product;
use Phppot\Config;
require_once __DIR__ . '/../config/Config.php';
require_once __DIR__ . '/../lib/Product.php';
$productModel = new Product();
if (! empty($_POST["keyword"])) {
$serach = "%" . $_POST['keyword'] . "%";
$productResult = $productModel->getProductByKeyword($serach, Config::MIN_SEARCH_RESULT_COUNT);
$featuredProductResult = $productModel->getFeaturedProductByKeyword($serach, $productResult[0]["featured"], Config::MIN_SEARCH_RESULT_COUNT);
$categoryResult = $productModel->getProductCategoryByKeyword($serach, Config::MIN_SEARCH_RESULT_COUNT);
if (! empty($productResult)) {
?>
<div id="search-list">
<div class="search-section">
<label>Featured</label>
<?php
foreach ($featuredProductResult as $k => $v) {
?>
<div class="product-row">
<img class="image-search-result"
src="<?php echo $featuredProductResult[$k]["image"];?>
">
<div class="description"><?php echo $featuredProductResult[$k]["name"];?><br /><?php echo $featuredProductResult[$k]["description"];?></div>
</div>
<?php
}
?>
</div>
<?php
}
?>
<?php
if (! empty($productResult)) {
?>
<div class="search-section">
<label>Products</label>
<?php
foreach ($productResult as $k => $v) {
?>
<div class="product-row">
<img class="image-search-result"
src="<?php echo $productResult[$k]["image"];?>">
<div class="description"><?php echo $productResult[$k]["name"];?><br /><?php echo $productResult[$k]["description"];?></div>
</div>
<?php
}
?>
</div>
<?php
}
?><?php if (! empty($categoryResult)) {?>
<div class="category search-section">
<label>Category</label>
<?php foreach ($categoryResult as $i => $s) {?>
<div class="product-row">
<img class="image-search-result"
src="<?php echo $categoryResult[$i]["image"];?>"> <?php echo $categoryResult[$i]["name"];?>
</div>
<?php
}
?>
<?php
}
?></div>
</div>
<?php }?>
config/Config.php
<?php
/**
* Copyright (C) Vincy - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Vincy <vincy@phppot.com>
*/
namespace Phppot;
/**
* This class contains the configuration options
*/
class Config
{
const MIN_SEARCH_RESULT_COUNT = "3";
}
lib/Product.php
<?php
namespace Phppot;
require_once __DIR__ . '/../config/Config.php';
class Product
{
private $dbConn;
public function __construct()
{
require_once __DIR__ . '/../config/DataSource.php';
$this->dbConn = new DataSource();
}
function getProductByKeyword($serach, $limit)
{
$query = "SELECT * FROM tbl_product WHERE name like ? OR description like ? ORDER BY name LIMIT $limit";
$paramType = "ss";
$paramValue = array(
$serach,
$serach
);
$productResult = $this->dbConn->select($query, $paramType, $paramValue);
return $productResult;
}
function getFeaturedProductByKeyword($serach, $featured, $limit)
{
$query = "SELECT * FROM tbl_product WHERE (name like ? OR description like ?) AND (featured =?) ORDER BY name LIMIT $limit";
$paramType = "ssi";
$paramValue = array(
$serach,
$serach,
$featured
);
$featuredProductResult = $this->dbConn->select($query, $paramType, $paramValue);
return $featuredProductResult;
}
function getProductCategoryByKeyword($serach, $limit)
{
$query = "SELECT * FROM tbl_category WHERE name like ? ORDER BY name LIMIT $limit";
$paramType = "s";
$paramValue = array(
$serach
);
$categoryResult = $this->dbConn->select($query, $paramType, $paramValue);
return $categoryResult;
}
}
?>
Thus, we have implemented the eCommerce live search feature for an eCommerce website.
We have seen an AJAX-based implementation for the live search in PHP. It provided a dynamic live-search component for an eCommerce website.
We have seen the types of live search available in the existing eCommerce websites like Amazon.
I hope, it will help to gain some idea to add the live search filter to your eCommerce website. Thereby, it will let the customer have a quick look at the products and categories based on the search keyword.