Advanced php and mysql

Advanced Search using PHP

Advanced search provides more options to the user to filter and narrow down the search result. Advanced search will be convenient for the end users and a search implementation without advanced option will be useless in many cases. Even Google search has ‘advanced search’ option.

In a previous tutorial, we have seen simple PHP search to filter MySQL records with just one field to enter the search keyword and get results based on it. In this PHP article, let us enrich by adding more fields and options and implement the PHP advanced search by filtering the MySQL data.

In the advanced search form, we have inputs to search with respect to the exact or any one of a word from given phrase, to exclude given string and to search results that start with given word.

And also we can also choose the database column in which the search should be happening. I have also added PHP search example for highlighting keywords in the search results.

HTML Advanced Search Form

This code contains HTML form inputs for the advanced search option. On page load, it will show a single input to type the search keyword.

advanced-search-using-php

If you want to filter the results with more criteria, then the Advanced Search link will show more inputs to do the database search.

 
">
" /> Advance Search
>
" />
" />
" />

Creating Advance Search Condition in PHP

This code receives form inputs and forms MySQL query with the advanced search condition. If the user prefers database columns to search then the search will apply on that column. Otherwise, we will search in all the columns. The code is,

$v) < if(!empty($v)) < $queryCases = array("with_any_one_of","with_the_exact_of","without","starts_with"); if(in_array($k,$queryCases)) < if(!empty($queryCondition)) < $queryCondition .= " AND "; >else < $queryCondition .= " WHERE "; >> switch($k) < case "with_any_one_of": $with_any_one_of = $v; $wordsAry = explode(" ", $v); $wordsCount = count($wordsAry); for($i=0;$i<$wordsCount;$i++) < if(!empty($_POST["search"]["search_in"])) < $queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $wordsAry[$i] . "%'"; >else < $queryCondition .= "title LIKE '" . $wordsAry[$i] . "%' OR description LIKE '" . $wordsAry[$i] . "%'"; >if($i!=$wordsCount-1) < $queryCondition .= " OR "; >> break; case "with_the_exact_of": $with_the_exact_of = $v; if(!empty($_POST["search"]["search_in"])) < $queryCondition .= $_POST["search"]["search_in"] . " LIKE '%" . $v . "%'"; >else < $queryCondition .= "title LIKE '%" . $v . "%' OR description LIKE '%" . $v . "%'"; >break; case "without": $without = $v; if(!empty($_POST["search"]["search_in"])) < $queryCondition .= $_POST["search"]["search_in"] . " NOT LIKE '%" . $v . "%'"; >else < $queryCondition .= "title NOT LIKE '%" . $v . "%' AND description NOT LIKE '%" . $v . "%'"; >break; case "starts_with": $starts_with = $v; if(!empty($_POST["search"]["search_in"])) < $queryCondition .= $_POST["search"]["search_in"] . " LIKE '" . $v . "%'"; >else < $queryCondition .= "title LIKE '" . $v . "%' OR description LIKE '" . $v . "%'"; >break; case "search_in": $search_in = $_POST["search"]["search_in"]; break; > > > > $orderby = " ORDER BY id desc"; $sql = "SELECT * FROM links " . $queryCondition; $result = mysqli_query($conn,$sql); ?> 

Database Script with Structure and Data of the MySQL table

This database script is used to import the links table structure and the data to run this example PHP code.

-- Table structure for table `links` CREATE TABLE `links` ( `id` int(8) NOT NULL, `title` varchar(255) NOT NULL, `description` text NOT NULL, `votes` tinyint(2) DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- Dumping data for table `links` INSERT INTO `links` (`id`, `title`, `description`, `votes`) VALUES (1, 'Favorite Star Rating with jQuery', 'This tutorial is for doing favorite star rating using jQuery. It displays list of HTML stars by using li tags. These stars are highlighted by using CSS and jQuery based on the favorite rating selected by the user.', 1), (2, 'PHP RSS Feed Read and List', 'PHP\'s simplexml_load_file() function is used for reading data from xml file. Using this function, we can parse RSS feed to get item object array.', 0), (3, 'jQuery AJAX Autocomplete - Country Example', 'Autocomplete feature is used to provide auto suggestion for users while entering input. It suggests country names for the users based on the keyword they entered into the input field by using jQuery AJAX.', 0), (4, 'PHP CRUD with Search and Pagination', 'We have search options for searching the Name and Code columns by the given keywords posted via the search form. The search keyword is used to find match with the values of corresponding columns by using MySQL LIKE clause.', 0), (5, 'DropDown with Search using jQuery', 'Search is an useful feature for a HTML dropdown list. Especially it will increase user convenience to select items from the dropdown having long list. In this tutorial, we are going to list country dropdown with a search option.', 0), (6, 'PHP MySQL Date Range Search with jQuery DatePicker', 'how to search database records date between two given ranges. It will return the filtered results from database based on these dates input.', 0); -- Indexes for table `links` ALTER TABLE `links` ADD PRIMARY KEY (`id`); ALTER TABLE `links` MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; COMMIT; 

Leave a Reply Cancel reply

Источник

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.

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.

 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[] color: #0000ff;">$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 color: #0000ff;">$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']); ?>    rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />   style="width: 50%; margin: 0 auto;">  class="hidden-sm bg-info" style="padding: 10px;">  action="" method="post" > class="col-sm-3">  name="city" class="form-control">  value="0">Select City  foreach($turistCity as $city) < $checked = ($_POST['city'] == $city[city_id])? 'selected' : ''; echo ' value="'.$city[city_id].'" '.$checked.'>'.$city[city].' '; > ?>    class="col-sm-3">  name="place" class="form-control"> value="0">Select Visiting Place  foreach($visitingPlace as $place) < $checked1 = ($_POST['place'] == $place[vid])? 'selected' : ''; echo ' value="'.$place[vid].'" '.$checked1.'>'.$place[visiting_place].' '; > ?>    class="col-sm-3">  type="text" name="keyword" placeholder="Keword" value color: #ff0000;"> echo $_POST['keyword']; ?>" class="form-control" />   name="search" class="btn btn-primary">Search    class="hidden-md bg-warning" style="padding: 10px;">  cellpadding="10" cellspacing="10" class="table table-striped">   ID City Place History    $i = 1; if(count($searchdata) > 0 )< foreach($searchdata as $places) < echo ' '; echo ' '.$i.' '; echo ' '.$places[city].' '; echo ' '.$places[visiting_place].' '; echo ' '.$places[history].' '; echo ' '; $i++; > > else < echo ' colspan="4">No Search Result Found. '; >  ?>     

Источник

Читайте также:  Питон гост 28147 89
Оцените статью