etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP MYSQL Advanced Search Feature

In this article, you will learn how to develop advance search feature using PHP & MYSQL.

The advanced search feature provides more searching options to the users to filter the search result. 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 the user can find out the exact information that they are looking for. 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 exact what they want. That's why we are using the advanced search.

PHP MYSQL Advanced Search Feature

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

CREATE TABLE IF NOT EXISTS `tourist_city` (
  `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.


<?php 
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  C.city 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 on the browser. In this file, we have written HTML Form to search data. When user clicks on the 'Search' button, the form get submitted and the search results are displayed.


<?php
 include 'db.php';
 $model = new Db();
 $turistCity = $model->getTouristCity();
 $visitingPlace = $model->getVisitingPlaces();
 $searchdata = $model->getVisitinPlaceData($_POST['city'], $_POST['place'], $_POST['keyword']);
?>
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    </head>
    <body>
        <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>';
                }
                ?>
                </select>
            </div>
            <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>';
                    }
                    ?>
                </select>
            </div>
            <div class="col-sm-3">
                <input type="text" name="keyword" placeholder="Keword" value="<?php echo $_POST['keyword']; ?>"  class="form-control" /> 
            </div>
            <button name="search" class="btn btn-primary">Search</button>
        </form>
        </div>
        <div class="hidden-md bg-warning" style="padding: 10px;">
            <table cellpadding="10" cellspacing="10" class="table table-striped">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>City</th>
                    <th>Place</th>
                    <th>History</th>
                </tr>
                </thead>
                <tbody>
                <?php
                $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>';
                    $i++;
                }
                }
                else {
                    echo '<td colspan="4">No Search Result Found.</td>';
                }
                ?>
            </table>
        </div>
        </div>
    </body>
</html>




Related Articles

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 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




Most Popular Development Resources
Characteristics of a Good Computer Program
-----------------
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP Create Word Document from HTML
-----------------
How to encrypt password in PHP
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
How to add multiple custom markers on google map
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
jQuery File upload progress bar with file size validation
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple PHP File Cache
-----------------
Polling system using PHP, Ajax and MySql
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
PHP User Authentication by IP Address
-----------------
How to generate QR Code in PHP
-----------------
Calculate the distance between two locations using PHP
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Detect Mobile Devices in PHP
-----------------
Set and Get Cookies in PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
PHP Server Side Form Validation
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Programming Error Types
-----------------
PHP Sending HTML form data to an Email
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
How to print specific part of a web page in javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.