How to combine several dropdown list values in mysql query? - php

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

Related

I want to get values in PHP throughout a html form

Im new to PHP and want to get these arrays to send by a form, but cant manage to store it in a variable and access them
HTML
<form action="./index.php" method="post">
<select name="multicheckbox[]" multiple="multiple" class="4colactive">
<option value="LunVie" name="LunVie">Lunes a Viernes</option>
<option value="LunSab" name="LunSab">Lunes a Sábados</option>
<option value="Todos" name="Todos">Todos los días</option>
<option value="Otros" name="Otros">Otros</option>
</select>
<button type="submit">Enviar</button>
</form>
PHP
<?php
$values = $_POST["multicheckbox"];
echo $values[2];
?>
multicheckbox is an array, iterate over it.
foreach($_POST["multicheckbox"] as $check) {
echo $check . "<br />\n";
}
Also note options don't have names, the select has a name. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option
<select name="multicheckbox[]" multiple="multiple" class="4colactive">
<option value="LunVie">Lunes a Viernes</option>
<option value="LunSab">Lunes a Sábados</option>
<option value="Todos">Todos los días</option>
<option value="Otros">Otros</option>
</select>

Advanced search with ajax, php and mysql

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

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.

Using multiple PHP drop downs to filter MySQL table data

I am currently building a page that uses five separate drop down menus (static content) that when selected the combination of what is selected will filter my mysql query and display the correct results using those parameters.
I am a newbie in php and i don't know how to go about it
Here is the html code for index.php
<form action="search.php" method="post">
<p>Body Type</p>
<select class="form-control" name="bodytype">
<option value="" selected="selected">Any body type</option>
<option value="saloon">Saloons</option>
<option value="hatchback">Hatchbacks</option>
<option value="4 wheel drive">4 wheel drives</option>
<option value="station wagon">Station wagon</option>
<option value="pickup">Pickups</option>
<option value="motor bike">Motor bikes</option>
<option value="convertible">Convertibles</option>
<option value="bus">Buses, Danfos & Vans</option>
<option value="truck">Trucks</option>
</select>
<p>Condition</p>
<select class="form-control" name="condition">
<option value="" selected="selected">Any condition</option>
<option value="brand new">Brand new</option>
<option value="foreign used">Foreign used (Tokunbo)</option>
<option value="nigerian used">Nigerian used (Registered)</option>
</select>
<p>Fuel type</p>
<select class="form-control" name="fueltype">
<option value="" selected="selected">Any fuel type</option>
<option value="petrol">Petrol</option>
<option value="diesel">Diesel</option>
<option value="hybrid">Hybrid</option>
</select>
<p>Transmission</p>
<select class="form-control" name="transmission">
<option value="" selected="selected">Any transmission</option>
<option value="automatic">Automatic</option>
<option value="manual">Manual</option>
</select>
<p>Drive type</p>
<select class="form-control" name="drivetype">
<option value="" selected="selected">Any drive type</option>
<option value="2 wheel drive">2 wheel drive</option>
<option value="4 wheel drive">4 wheel drive</option>
</select>
<input name="search" type="submit" value="Search">
</form>`
This is the search.php
<body>
<?php
$selected_btype = $_POST['bodytype']; // Storing Selected Value In Variable
$selected_condition = $_POST['condition'];
$selected_fueltype = $_POST['fueltype'];
$selected_makemodel = $_POST['makemodel'];
$selected_transmission = $_POST['transmission'];
$selected_location = $_POST['location'];
$selected_dtype = $_POST['drivetype'];
$selected_year= $_POST['year'];
$selected_dsetup= $_POST['drivesetup'];
$query="SELECT * FROM vehicle WHERE(body_type=$selected_btype) OR
(condition='$selected_condition') OR (fuel_type='$selected_fueltype') OR
(make_model='$selected_makemodel') OR (transmission='$selected_transmission') OR
(location='$selected_location') OR (drive_type='$selected_dtype') OR
(year='$selected_year') OR (drive_setup='$selected_dsetup')";
$result=mysql_query($query);
if($result)
{
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['sn']."</td>";
echo "<td>".$row['body_type']."</td>";
echo "<td>".$row['make_model']."</td>";
echo "<td>".$row['location']."</td></tr>";
echo "<td>".$row['year']."</td>";
echo "<td>".$row['condition']."</td>";
echo "<td>".$row['transmission']."</td>";
echo "<td>".$row['description']."</td></tr>";
echo "<td>".$row['images']."</td></tr>";
}
}else{
die(mysql_error());
}
?>
The output of search.php:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition='nigerian used') OR (fuel_type='') OR (make_model='peugeot'' at line 1
There are a few issues with your code:
Firstly, condition is a MySQL reserved word and needs to be wrapped in backticks.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either wrap it in backticks or rename it to another word.
$query="SELECT * FROM vehicle WHERE(body_type=$selected_btype) OR
(`condition`='$selected_condition')
Notice where the error is pointing to:
for the right syntax to use near 'condition='nigerian used')
^
Then there's WHERE(body_type=$selected_btype)
The $selected_btype variable needs to be wrapped in quotes, since string values are involved.
WHERE(body_type='$selected_btype')
Footnotes:
You should consider using mysqli with prepared statements, or PDO with prepared statements, they're much safer, because your present code is open to SQL injection.
In your query, the body type selection is not encapsulated in quotes like others, but it is a string so it needs to be like this
$query="SELECT * FROM vehicle WHERE(body_type=<b>'</b>$selected_btype<b>'</b>) OR......

Categories