Advanced search with ajax, php and mysql - php

I'm building an advanced search with ajax, php and mysql. below is the working code for the search form (html) the AJAX call and the php script that handles the request. However, the issue i'm facing is how to make a dynamic mysql query.
For example if the user searches "Hilton Hotel" in the search input, selects "accommodation" as the industry_types and "Hotel" as the sub_industry_type and selects "London" as the city. How can I write a query that will take all of these inputs into consideration?
Please note: in the search.php i have included the query for handling a keyword submitted in the user_search_input input.
Index.php (HTML):
<form class="user_search_form" action="" method="post">
<input type="text" class="user_search_input" placeholder="search" />
<select class="industry_types" name="industry_types" id="industry_types">
<option value="">Select an industry</option>
<option value="Accommodation">Accommodation</option>
<option value="Food_Drink">Food & Drink</option>
<option value="Entertainment">Entertainment</option>
<option value="Retail">Retail</option>
<option value="Telecommunications">Telecommunications</option>
<option value="Transportation">Transportation</option>
</select>
<select class="Accommodation sub_industry_type" name="Accommodation" id="sub_industry_type">
<option value="0">Select Accommodation subcategory</option>
<option value="Bed and Breakfasts">Bed and Breakfasts</option>
<option value="Hotel">Hotels</option>
<option value="Hotel">Hostels</option>
<option value="Resturant">Resorts</option>
<option value="Serviced apartments">Serviced apartments</option>
</select>
<select class="Food_Drink sub_industry_type" name="Food_Drink" id="sub_industry_type">
<option value="0">Select Cuisine subcategory</option>
<option value="Resturant">Restaurants</option>
<option value="Cafes">Cafes</option>
<option value="Bars and Pubs">Bars and Pubs</option>
<option value="Tourist Agency">Night clubs</option>
</select>
<select class="Entertainment sub_industry_type" name="Entertainment" id="sub_industry_type">
<option value="0">Select Entertainment subcategory</option>
<option value="Performing Arts">Performing Arts</option>
<option value="Cinemas">Cinemas</option>
<option value="Resorts and Casinos">Resorts and Casinos</option>
<option value="Amusement Parks and Attractions">Amusement Parks</option>
<option value="Museums">Museums</option>
<option value="Outdoor activities">Outdoor activities</option>
<option value="Media and Entertainment Other">Entertainment Other</option>
</select>
<select class="Retail sub_industry_type" name="Retail" id="sub_industry_type">
<option value="0">Select Retail subcategory</option>
<option value="Beer, Wine and Liquor Stores">Beer, Wine and Liquor Shops</option>
<option value="Clothing and Shoe Stores">Clothing and Shoe Shops</option>
<option value="Electronic Shops">Electronic Shops </option>
<option value="Jewelry, Luggage, and Accessories">Jewelry, Luggage, and Accessories</option>
<option value="Sporting Goods, Hobby, Books and Music Stores">Sporting Goods, Hobby, Books and Music Stores</option>
<option value="Internet Businesses">Internet Businesses</option>
<option value="Retail Others">Retail Others</option>
</select>
<select class="Telecommunications sub_industry_type" name="Telecommunications" id="sub_industry_type">
<option value="0">Select Telecommunications subcategory</option>
<option value="Telephone Service Providers and Carriers">Telephone Service Providers</option>
<option value="Telecommunications Other">Telecommunications Other</option>
</select>
<select class="Transportation sub_industry_type" name="Transportation" id="sub_industry_type">
<option value="0">Select Transportation subcategory</option>
<option value="Car Rental">Car Rentals</option>
<option value="Taxi, Buses and Transit Systems">Taxi Services</option>
<option value="Travel Agents">Travel Agents</option>
</select>
<select name="select_city" class="select_city">
<option value="">City</option>
<option value="">London</option>
<option value="">New York</option>
<option value="">Paris</option>
</select>
<input type="submit" value="search" class="search_btn" />
</form>
Index.php (AJAX):
$('.user_search_form').submit(function(e){
e.preventDefault();
var $search_input = $('.user_search_input').val();
var $industry_general = $('.industry_types').val();
var $industry_spesific = $('.sub_industry_type').val();
var $selected_city = $('.select_city').val();
var url = "search.php";
$.ajax({ //create an ajax request to load_page.php
type: "POST",
url: url,
data:{search_input: $search_input, industry_general: $industry_general, industry_spesific: $industry_spesific, selected_city: $selected_city},
dataType: "html", //expect html to be returned
success: function(date){
$('#search_results').html(date);
}
})
});
search.php (The issue):
<?php include 'includes/db_connect.php';
$search_input = $_POST['search_input'];
$industry_general = $_POST['industry_general'];
$industry_spesific = $_POST['industry_spesific'];
$selected_city = $_POST['selected_city'];
if(!empty($search_input)){
$sql = $dbh->prepare("SELECT * FROM table WHERE company_name LIKE :company_name OR company_keywords LIKE :company_keywords OR company_city LIKE :company_city OR company_email LIKE :company_email");
$sql->bindValue(':company_name', '%' . $search_input . '%', PDO::PARAM_STR);
$sql->bindValue(':company_keywords', '%' . $search_input . '%', PDO::PARAM_STR);
$sql->bindValue(':company_city', '%' . $search_input . '%', PDO::PARAM_STR);
$sql->bindValue(':company_email', '%' . $search_input . '%', PDO::PARAM_STR);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
}
elseif(!empty($industry_general)){
// if industry_general is not empty
}
elseif(!empty($industry_spesific)){
// if industry_spesific is not empty
}
elseif(!empty($selected_city)){
// if selected_city is not empty
}?>

How about this snippet?
// columns that should contain either of the search_input words
$searchTermCols = [
'company_name',
'company_keywords',
'company_city',
'company_email'
];
$data = $_POST; // copy $_POST array to a variable so you can safely alter keys/values
$searchInput = $data['search_input']; // tmp store search_input so you can unset it for the rest of the code
unset($data['search_input']); // unset unnecessary keys (if you have any). like in your case you want to do different stuff with that key=>value
//unset($data['some_other_unwanted_input_doing_other_stuff']); // or another one
$searchInputParts = preg_split('/\s+/', $searchInput); // explode by whitespace
$searchInput = implode('|',$searchInputParts); // for REGEXP search in mysql to search each word occurrence in a column
foreach($data as $key=>$val) { // loop through copied array
$sqlParts1[] = $key.' LIKE :'.$key;
}
foreach($searchTermCols as $key) { // loop through columns that should contain either of the words
$sqlParts2[] = $key.' REGEXP :'.$key;
}
$andParts = implode(' AND ',$sqlParts1); // these options must exists in the columns
$orParts = implode(' OR ',$sqlParts2); // these options must exists in the columns
$qryStr = "SELECT * FROM table WHERE ";
$qryStr .= "($andParts) AND ($orParts)"; // concatenate both similar but different queries and append to query
$sql = $dbh->prepare($qryStr);
foreach($data as $key=>$val) {
$sql->bindValue(':'.$key, '%' . trim($val) . '%', PDO::PARAM_STR);
}
foreach($searchTermCols as $key) {
$sql->bindValue(':'.$key, $searchInput, PDO::PARAM_STR);
}
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
UPDATE
You can copy $_POST to another variable and unset keys you dont want in the query. See first two added lines and the $data variable set to loop through.
UPDATE 2 Important..
Your form input's name attributes need to match your database table's columns. So for example:
<input type="text" name="company_name" id="company_name">
If your db table's column name is "company_name".
UPDATE 3
For fun i added the requirements explained in your comment. I do not have your table structure so i did not test it...

Related

Get multiple select data from Bootstrap Select using PHP

I'm using bootrap-select plugin
1: https://github.com/snapappointments/bootstrap-select/ I'm trying to grab data from it. I try so many ways but it doesn't work out. So the input is like this:
<div class="col-9">
<select id="generals" name="generals" class="form-control kt-selectpicker" multiple title="Choose one of the following...">
<optgroup label="Passport">
<option value="passport_number">Number</option>
<option value="passport_date">Date of issuance</option>
<option value="passport_expired">Date of expiry</option>
<option value="passport_office">Issuing Office</option>
</optgroup>
<optgroup label="Personal">
<option value="applicant_id">Applicant Id</option>
<option value="first_name">First Name</option>
<option value="first_name">Middle Name</option>
<option value="last_name">Last Name</option>
<option value="address">Address</option>
<option value="crew_id">Crew Id</option>
<option value="email">Email</option>
<option value="mobile_number">Mobile Number</option>
</optgroup>
</select>
</div>
I try to grab using PHP foreach and for loops, implode or explode but it doesn't work since it said it does not an array. When i see the Header data sent is like this:
so how can i get this data? I'm using Ajax to send data. Here's the Fiddle if you want to see it: https://jsfiddle.net/4u6xc9kd/
It's easy, you just put the input name like this name="generals[]" in your input select and the use foreach like this:
$generals = '';
if (isset($_POST['generals'])){
foreach ($_POST['generals'] as $value){
$generals .= $value . ', ';
}
}

How to combine several dropdown list values in mysql query?

<form method="post" action="search.php">
<select name="Num[]">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op[]">
<option value="">Select One</option>
<option value=">4">>4</option>
<option value=">2">>2</option>
</select>
<br />
<select name="num2[]">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2[]">
<option value="">Select One</option>
<option value="<20000"><20000</option>
<option value="<40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</form>
Here is my code to provide a dropdown list for the user. It will act as a filter to generate more specific result through mysql and don't get the logic to combine these dropdown values.
I would like to have something like:
Select * from hotel where price < 40000;
and I will provide all keywords after "Where".
Select boxes name are defined as array in html and your requirement is a user can select a single option in a select box. So you need to update the name of select boxes. You no need to add < in select box values, These conditions used at server end. I have corrected the HTML.
<form method="post" action="">
<select name="Num">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op">
<option value="">Select One</option>
<option value="4">>4</option>
<option value="2">>2</option>
</select>
<br />
<select name="num2">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2">
<option value="">Select One</option>
<option value="20000"><20000</option>
<option value="40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit" name="search_btn"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
Server Side code for handle selected values and add to query.
if(isset($_POST['search_btn'])){
$conditons = array();
if(isset($_POST['Num'])){
$conditons[] = '`people` = "'.$_POST['Num'].'"';
}
if(isset($_POST['op'])){
$conditons[] = '`option` < '.$_POST['op'];
}
if(isset($_POST['price'])){
$conditons[] = '`price` = '.$_POST['price'];
}
if(isset($_POST['op2'])){
$conditons[] = '`op2` < '.$_POST['op2'];
}
$conditons = implode(' & ', $conditons);
echo $query = 'select * from hotel where '.$conditons;
}
You an update your real field name in conditions. After added conditions, result query will be as -
select * from hotel where `people` = "numofpeople" & `option` < 4 & `op2` < 20000
Here is a very generic example that I just put together. This code is not tested, but I have written like this before.
<?php
// Checks to see if post variables are available
if(isset($_POST)) {
// Creates original command
$query = "SELECT * FROM hotel WHERE "
// gets each value from the post
foreach($_POST as $key => $value) {
$query .= $key . "=" . $value . "AND ";
}
// Removes the trailing "AND "
$query = substr($query, 0, -4);
echo $query;
}
If you need to switch things up depending on key, you can just do a switch inside of the foreach statement that will check the key value. The key is the "name" attr that is assigned in the HTML that you are posting from.
This method is also not sanitized because I did not get a response to which connection type you are using, but it shouldn't be that hard. If you need me to write it, then I would be more than happy to do so.

How do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

passing values to sql through check boxes and dropdowns

How can i pass Drop down values to sql database and also the check box for example if a user selects English and maths than the value inserted in to the database would be 1 or else the value would be 0
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<input type="checkbox" name="Math" value="Math">Math<br>
<input type="checkbox" name="English" value="English">English<br>
<input type="checkbox" name="HealthScience" value="HealthScience">Health Science<br>
<input class="sub_reg" type="submit" value="Register Subjects" />
</form>
this is how my database looks like
First, your <select id="year_sel"> needs a name attribute to post ->
<select id="year_sel" name="year_sel" >
Since you are using <form> the default is get, so you would get the selected value in $_GET
$year_sel = $_GET['year_sel'];
If you changed it to
<form method="post">
then you would get it in $_POST
$year_sel = $_POST['year_sel']
Second, checkboxes are only posted if checked, so you can use isset() to set a value using a ternary -
$math = isset($_GET['Math']) ? 1 : 0;
$english = isset($_GET['English']) ? 1 : 0;
...[rest of your checkboxes]...
swap $_GET/$_POST like the select
$math = isset($_POST['Math']) ? 1 : 0;
$english = isset($_POST['English']) ? 1 : 0;
<select id="year_sel" name="year_sel">
<option value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
on your form action something.php file use this to get the select value
$language = $_POST["year_sel"]; // chose whetever your form method
establish the database connection please do refer some tutorials (if you don't know )
write the mysqli insert command like
$SQL = "INSERT INTO yourtable (language) VALUES ('$language')";
mysqli_real_escape_string($sql);
$result = mysqli_query($sql) or die (mysqli_error());
now you can insert this value in your mysql or any database table
this is not tested
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel" name="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<?php
$variable = $_POST["year_sel"];
?>
Should mention the HTML ELEMENT name to get the value.

How I explode this kind of string in PHP?

I have a dropdown to display price ranges for searching.
HTML for dropdown:
<select name="price">
<option value="">All (-)</option>
<option value="">Rs.400 to Rs.1,000 (3)</option>
<option value="">Rs.1,000 to Rs.2,000 (6)</option>
<option value="">Rs.2,000 to Rs.4,000 (1)</option>
<option value="">Rs.4,000+ (1)</option>
</select>
Using this option values, now I need to separate first and second price from user selection.
Eg. If someone select Rs.400 to Rs.1,000 (3), then I need to get 400 and 1,000.
Can anybody tell me how can I do this in php. I tired it with php explode. but I could not figure this out correctly.
Hope somebody may help me out.
Thank you.
What about something like this:
HTML
<select name="price">
<option value="all">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="Over">Rs.4,000+ (1)</option>
</select>
PHP
<?php
//Get the data from the form
$price = $_POST['price'];
$prices = explode("|", $price);
?>
For example, if the user selects "Rs.400 to Rs.1,000", the value of $prices will be:
$price[0] = "400";
$price[1] = "1000";
I hope that helps. If it doesn't, I suppose I wasn't clear on what you were asking.
Inspired by a previous answer. I'd suggest.
HTML
<select name="price">
<option value="|">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="4000|">Rs.4,000+ (1)</option>
</select>
PHP
<?php
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return false;
}
$price_selected = isset($_REQUEST['price']) && trim($_REQUEST['price'])!="" ? $_REQUEST['price'] : "|"; // sets a default value
list($lower, $upper) = array_map('get_numeric',explode('|', $price_selected, 2));
var_dump($lower); // false when there's no lower limit
var_dump($upper); // false when there's no upper limit
?>

Categories