PHP MySql Advanced Search Feature

In this article, you will learn how to develop an advanced search feature usingĀ PHP and MySQL.

The advanced search feature provides more search options for users to filter the search results. When used for searching the Web, an advanced search gives additional information and search query filter options to the user, which helps refine the search and allows the user to find the exact information that they are looking for. A normal search is not relevant when the search query returns too many records. It will become a hectic task for the user to find out exactly what they want. That's why we are using advanced search.

PHP MYSQL Advanced Search Feature

Here, we have taken an example of a tourism search filter. For this, we first created two MySQL tables named 'tourist_city' and 'visiting_places' and inserted some records into them. You can use the database if you already have otherwise, you can create it manually or copy and paste the following queries into your database.

  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `city` varchar(100) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`city_id`)

CREATE TABLE IF NOT EXISTS `visiting_places` (
  `vid` int(11) NOT NULL AUTO_INCREMENT,
  `city_id` int(11) NOT NULL,
  `visiting_place` varchar(100) NOT NULL,
  `history` varchar(1000) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`vid`)

INSERT INTO `tourist_city` (`city_id`, `city`, `is_enabled`) VALUES
(1, 'Delhi', 1),
(2, 'Mumbai', 1),
(3, 'Goa', 1),
(4, 'kolkata', 1);

INSERT INTO `visiting_places` (`vid`, `city_id`, `visiting_place`, `history`, `is_enabled`) VALUES
(1, 1, 'Red Fort', 'The Red Fort was the residence of the Mughal emperor for nearly 200 years, until 1857. It is located in the centre of Delhi and houses a number of museums. In addition to accommodating the emperors and their households, it was the ceremonial and political centre of Mughal government and the setting for events critically impacting the region.[', 1),
(2, 1, 'Lotus Temple', 'The Lotus Temple, located in New Delhi, India, is a Bahai House of Worship completed in 1986. Notable for its flowerlike shape, it serves as the Mother Temple of the Indian subcontinent and has become a prominent attraction in the city', 1),
(3, 2, 'Gateway of India', 'The Gateway of India is a monument built during the 20th century in Mumbai City of Maharashtra state in Western India.', 1),
(4, 2, 'Elephanta Caves', 'Elephanta Caves are a network of sculpted caves located on Elephanta Island, or Gharapuri (literally "the city of caves") in Mumbai Harbour, 10 kilometres (6.2 mi) to the east of the city of Mumbai in the Indian state of Maharashtra.', 1),
(5, 3, 'Marine Drive', 'Marine Drive is a 3.5-kilometre-long boulevard in South Mumbai in the city of Mumbai. It is a ''C''-shaped six-lane concrete road along the coast, which is a natural bay. ', 1),
(6, 3, 'Fort Aguada', 'The fort was constructed in 1612 to guard against the Dutch and the Marathas. It was a reference point for the vessels coming from Europe at that time.', 1),
(7, 4, 'Victoria Memorial', 'The Victoria Memorial is a large marble building in Kolkata (formerly Calcutta), West Bengal, India, which was built between 1906 and 1921.', 1),
(8, 4, 'Dakhshineswar Tample', 'The Victoria Memorial is a large marble building in Kolkata (formerly Calcutta), West Bengal, India, which was built between 1906 and 1921.', 1);

1. db.php

Here, we have written the database connection code and defined functions to fetch data from the created tables. The function 'getVisitinPlaceData()' returns the data of search results. Make sure to replace the 'hostname', 'username', 'password', and 'database' with your database credentials.

class Db {
    private $hostname = 'hostname';
    private $username = 'username';
    private $password = 'password';
    private $database = 'database';
    private $conn = NULL;
    public function __construct() { 
        $this->conn = mysqli_connect($this->hostname, $this->username, $this->password, $this->database); 
        if(!$this->conn) {
            echo 'Database not connected';
    public function getTouristCity(){
        $query = "SELECT * FROM tourist_city WHERE is_enabled = '1'";
        $result = mysqli_query($this->conn, $query);
        return $result;
    public function getVisitingPlaces(){
        $query = "SELECT * FROM visiting_places WHERE is_enabled = '1'";
        $result = mysqli_query($this->conn, $query);
        return $result;
    public function getVisitinPlaceData($cityid, $placeid , $keyword){
        $sWhere = '';
        $where = array();
        if($cityid > 0) {
            $where[] = 'V.city_id = '.$cityid.' AND V.is_enabled = "1"';
        if($placeid > 0) {
            $where[] = 'V.vid = '.$placeid;
        if($keyword != '') {
            $keyword = trim($keyword);
            $where[] = "( V.visiting_place LIKE '%$keyword%' OR  V.history LIKE '%$keyword%'  OR LIKE '%$keyword%' )";
        $sWhere     = implode(' AND ', $where);
        if($sWhere) {
            $sWhere = 'WHERE '.$sWhere;
        if(($cityid > 0) || ($placeid > 0) || ($keyword != '')) {
            $query = "SELECT * FROM visiting_places AS V JOIN tourist_city AS C ON C.city_id = V.city_id $sWhere ";
            $result = mysqli_query($this->conn, $query);
            return $result;

2. index.php

This is the main file that we will call in the browser. In this file, we have written an HTML form to search for data. When a user clicks on the 'Search' button, the form gets submitted, and the search results are displayed.

 include 'db.php';
 $model = new Db();
 $turistCity = $model->getTouristCity();
 $visitingPlace = $model->getVisitingPlaces();
 $searchdata = $model->getVisitinPlaceData($_POST['city'], $_POST['place'], $_POST['keyword']);
<!DOCTYPE html>
        <link rel="stylesheet" href="" />
        <div style="width: 50%; margin: 0 auto;">
        <div class="hidden-sm bg-info" style="padding: 10px;"> 
        <form action="" method="post" > 
            <div class="col-sm-3"> 
                <select name="city" class="form-control">
                <option value="0">Select City</option>
                <?php foreach($turistCity as $city) {
                    $checked = ($_POST['city'] == $city[city_id])? 'selected' : '';
                    echo '<option value="'.$city[city_id].'" '.$checked.'>'.$city[city].'</option>';
            <div class="col-sm-3"> 
                <select name="place" class="form-control">
                    <option value="0">Select Visiting Place</option>
                    <?php foreach($visitingPlace as $place) { 
                        $checked1 = ($_POST['place'] == $place[vid])? 'selected' : '';
                        echo '<option value="'.$place[vid].'"  '.$checked1.'>'.$place[visiting_place].'</option>';
            <div class="col-sm-3">
                <input type="text" name="keyword" placeholder="Keword" value="<?php echo $_POST['keyword']; ?>"  class="form-control" /> 
            <button name="search" class="btn btn-primary">Search</button>
        <div class="hidden-md bg-warning" style="padding: 10px;">
            <table cellpadding="10" cellspacing="10" class="table table-striped">
                $i = 1;
                if(count($searchdata) > 0 ){
                foreach($searchdata as $places) {
                    echo '<tr>';
                        echo '<th>'.$i.'</th>';
                        echo '<td>'.$places[city].'</td>';
                        echo '<td>'.$places[visiting_place].'</td>';
                        echo '<td>'.$places[history].'</td>';
                    echo '</tr>';
                else {
                    echo '<td colspan="4">No Search Result Found.</td>';

Related Articles

PHP calculate percentage of total
Insert image in database using PHP
PHP Web Scraping Documentation
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP multiple file upload
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Recover forgot password using PHP and MySQL

Read more articles

General Knowledge

Learn Popular Language