PHP search with few parameters - php

I have an query that I am trying to do search with multiple parameters to sort my data response from sql.
The query code :
$sql = "SELECT * FROM `apartments` WHERE `building_num`='{$i}' ORDER by `apartment_num` ASC";
The search form :
<form method="GET">
<input type="hidden" name="page" value="price">
<select class="styled-select2" name="type">
<option value="0">Apartment type</option>
<option value="דופלקס">Duplex</option>
<option value="דירה">Apartments</option>
<option value="דירת גן">דירת גן</option>
</select>
<select class="styled-select2" name="rooms">
<option value="0">rooms</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="5">5</option>
</select>
<select class="styled-select2" name="price">
<option value="0">Price</option>
<option value="700000-800000">700,000-800,000 ₪ </option>
<option value="800000-900000">800,000-900,000 ₪</option>
<option value="900000-1000000">900,000-1,000,000 ₪</option>
<option value="1000000-1100000">1,000,000-1,100,000 ₪</option>
<option value="1100000-1200000">1,100,000-1,200,000 ₪</option>
<option value="1200000-1300000">1,200,000-1,300,000 ₪</option>
<option value="1300000-1400000">1,300,000-1,400,000 ₪</option>
<option value="1400000">1,400,000 up</option>
</select>
<input type="hidden" name="action" value="search">
<button type="submit">Search</button>
</form>
There are three parameters but they are not required, could the customer only use 'apartment type' AND 'Price' OR only one parameter, I tried for few hours to write query with no success, Any one can help ?
// Vars on table apartments
// Rooms - > Rooms
// Price -> price
// Apartment type -> type

1st of all, there's no direct link between and query (or queries) and tge options you're giving to the customer...
If you want to then you can allow the customer to fill some of the fields and if you don't then no... it's a matter of decision, from which derives the development
There's missing example code, so I can obly answer regarding the query and add some remarks
Since you've given specific select options, then you should use it for specific searches
I would also use some validations on the $_POST information returned
Regarding the query, I need to assume that all of the options are saved in the apartments table, under that, then the query should be something like this :
$sql = "SELECT * FROM `apartments` WHERE
rooms = $rooms
OR `type` = $type
OR (price BETWEEN *$range_min* AND *$range_max*)
ORDER by `apartment_num` ASC";
If you want all parameters combined you should use AND instead of OR
and, again, you can decide you want both and use different queries for each scenario the user givea

In this case you have to build dynamic query as below :-
$sql = "SELECT * FROM `apartments` WHERE ";
$condition = "";
$condition .= ($rooms=='')?"":" or 'rooms'= $rooms ";
$condition .= ($type=='')?"":" or 'type'= $type ";
$condition .= ($price=='')?"":" or prince bewteen 'range_min' AND 'range_max'";
$sql .= $condition;
$sql .= " ORDER by `apartment_num` ASC";
In this way you can make all three filters free to select or not.

Related

MYSQL for a 3 part search (Online Audio Software) - Search - Genre - & Catagory

I have a Project website that I am stuck in and although I can create a relatively working search engine using LIKE Wildcards , I cannot build a Professional and accurate Search Engine that would cover all 3 optional criteria's (Title , Genre & Category). And also show Relevant results if none are at first found.
If I select All 3 Criteria's at once I can often get a negative result even though there is a relative result to be found.
(I am really struggling to explain myself it is so complicated for me to get my head around)
The best way to show you is to show you my code.
Hopefully somebody will be able to advise me the best way to approach the search engine.
My intentions are to have a search that will show the correct results regardless of the order of the criteria and if no results are found then to show Relevant or similar results.
It has become quite a challenge.
My attempts at resolving the issue have been different formats of the query including LIKE wildcards. and no matter which way round i format i find problems in the search results.
Basically. if anybody can provide a query that they think would work, as in will produce results no matter what, I will try it.
My main problem is when there is no results found it is not showing the next best relevant set of results.
I have been going around in circles going through different queries and upto yet have not hit the nail on the head (so to say)
if (!empty($search)) {
if (!empty($genre)){$query="select * from audiolovedb WHERE MATCH (`title`) AGAINST ('$search') AND (`genre`) LIKE '$genre' ORDER BY `title` LIKE '$search%' DESC, `title` limit $amount "; }
else {$query="select * from audiolovedb WHERE MATCH (`title`) AGAINST ('$search') AND (`catagory`) LIKE '$catagory' ORDER BY `title` LIKE '$search%' DESC, `title` limit $amount "; }
}else {
if (!empty($genre)){$query="select * from audiolovedb WHERE (`genre`) LIKE '$genre%' ORDER BY `genre` LIKE '$genre' DESC, `genre` limit $amount "; }
else {$query="select * from audiolovedb WHERE (`catagory`) LIKE '$catagory%' ORDER BY `catagory` LIKE '$catagory' DESC, `catagory` limit $amount ";}
}
$stat=$db->prepare($query);
$stat->execute(array());
$count = $stat->rowCount();
And the form that sends the GET data
<form method="GET" action='index.php'> <!--Ends further Down-->
<select id='genregrab' name='genre' class='menusmall'>
<optgroup label='Genre'>
<option value="">All Genres</option>
<option value="House">House</option>
<option value="House">House</option>
<option value="Hard House">Hard House</option>
<option value="Tech House">Tech House</option>
<option value="Deep House">Deep House</option>
<option value="Future House">Future House</option>
<option value="Tribal House">Tribal House</option>
<option value="Tropical House">Tropical House</option>
<option value="EDM">EDM</option>
<option value="DnB">DnB</option>
<option value="Drum and Bass">Drum And Bass</option>
</select>
<select id='catagorygrab' name='catagory' class='menusmall'>
<optgroup label='Software'>
<option value="Windows">Windows Pc</option>
<option value="Mac OSX">Mac OSX</option>
<optgroup label='Audio'>
<option value="Samples" >Samples</option>
<option value="Presets">Presets</option>
<option value="Additional Libraries">Libraries</option>
<option value="SFX">SFX</option>
<option value="Vocals">Vocals</option>
<option value="Sound">Sound FX</option>
<option value="Film">Film/TV/Game</option>
<optgroup label='Project'>
<option value="MiDi">MiDi</option>
<option value="Projects">Projects</option>
<option value="Templates">Templates</option>
<optgroup label='Learning'>
<option value="Video">Video</option>
<option value="eBooks">eBooks</option>
<optgroup label='Addons'>
<option value="Skins">Skins</option>
<option value="Extras">Extras</option>
</select>
<!-- add amount selected previously to amount box -->
<?php $genre = implode(' ', array_slice(explode(' ', $genre), 0, 1)); ?>
<script type="text/javascript">
document.getElementById('catagorygrab').value = '<?php echo $catagory ?>'
document.getElementById('genregrab').value = '<?php echo $genre ?>'
</script>
<!--- search bar --->
<div class="search-input">
<input id='search' type="text" name='search' placeholder="Random Products" value="<?php echo $search ?>">
</div>
<div class="search-btn">
<button><i class="lni lni-search-alt"></i></button>
</div>
</form>

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
}

HTML Form Select default value from PHP Echo _Post

I have a html form where people select to filter the mysql results, example
<select name="display">
<option value="9999" selected>Display all results</option>
<option value="10">10 results only</option>
<option value="20">20 results only</option>
<option value="50">50 results only</option>
<option value="100">100 results only</option>
</select>
But if people select lets say 50 results per page, after form submit I want the option 50 results only to get marked as selected like this
<option value="50" selected>50 results only</option>
The question is How to do this using PHP POST or GET from the form
As I said in comments, assign a variable to a POST array and set it in your LIMIT in the query.
// you can also use isset instead of empty here and GET instead of POST
if(!empty($_POST['display'])) {
$limit = (int)$_POST['display']; // ensure the value is an integer
}
Then place the $limit variable in your query for LIMIT.
I.e.: (and as basic MySQL)
SELECT col1, col2, col3 FROM TABLE WHERE col_x = 'xxx' LIMIT $limit
The question though is a bit unclear so there isn't much else I can add to this.
Sidenote: LIMIT (with SELECT) accepts additional parameters. I.e.: LIMIT 0, 50
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
http://dev.mysql.com/doc/refman/5.7/en/select.html
Edit:
"after form submit I want the option 50 results only to get marked as selected"
In order to keep the value selected, use a conditional statement in the select's options and check if it equals to something:
Sidenote: This will only work if your entire code is inside the same file.
<?php
if(!empty($_POST['display'])) {
$limit = $_POST['display'];
$selected = 'selected';
}
?>
<form action="" method="post">
<select name="display">
<option value="9999" <?php if(isset($selected) && $limit==9999 ) {echo $selected; } ?>>Display all results</option>
<option value="10" <?php if(isset($selected) && $limit==10) {echo $selected; } ?>>10 results only</option>
<option value="20" <?php if(isset($selected) && $limit==20){echo $selected; } ?>>20 results only</option>
<option value="50" <?php if(isset($selected) && $limit==50){echo $selected; } ?>>50 results only</option>
<option value="100" <?php if(isset($selected) && $limit==100){echo $selected; } ?>>100 results only</option>
</select>
<input type="submit" value="submit">
</form>
You can add in the rest of your code.

Filter search based on selected drop downs in PHP

I have a Search form to search products.
<form method="get" action="search.php">
<select name="minprice">
<option value="">Min price</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
<option value="500">500</option>
</select>
<select name="maxprice">
<option value="">Max price</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="300">300</option>
<option value="400">400</option>
<option value="500">500</option>
</select>
<select name="type">
<option value="">type</option>
<option value="electric">electric</option>
<option value="other">other</option>
</select>
<select name="brand">
<option value="">type</option>
<option value="asus">ASUS</option>
<option value="ms">MS</option>
<option value="other">other</option>
</select>
<input type="submit" name="search" value="search">
</form>
In search.php page, i need results based only on what selected.
If i selected single list, i need that result only.
Example : I selected min price=100 , then i need to select products with minimum price 100 only...
I have tried this method , but it is not easy in my case, i am sure there is another way to implement this.
Any experts??
Any help / Ideas greatly appreciated..
EDIT
if(isset($_GET['minprice'])
{
$minprice=$_GET['minprice'];
$query="SELECT * FROM products WHERE price>='$minprice'";
}
else if()....
{ }
I am currently doing this way, But on next conditions not taking...
My Questions:
Do only this way to get the results?
Any change needed on $_GET[''] method like !="" or empty().
First, change your form from get to post. While users can manipulate POST, it's far easier to manipulate GET.
<form method="post" action="search.php">
Second, evaluate all of the POST variables first, and then compose your database query.
$minprice = isset($_POST['minprice']) ? $_POST['minprice'] : null;
$maxprice = isset($_POST['maxprice']) ? $_POST['maxprice'] : null;
$type = isset($_POST['type']) ? $_POST['type'] : null;
$brand = isset($_POST['brand']) ? $_POST['brand'] : null;
NOTE: I'm not sure what database type you're using, but you should use prepared statements with these variables when building your query. It's also a good idea to limit the possible values in your variables -- so, for example, if you expect price to always be a decimal number, you should cast the string to float.
You can then use something like the following for your query. I'm going to assume you're using a mysql database.
"SELECT <columns> FROM products WHERE minprice >= ISNULL(<$minprice variable>,minprice) AND maxprice <= ISNULL(<$maxprice variable>,maxprice) AND type = ISNULL(<$type variable>,type) AND brand = ISNULL(<$brand variable>,brand)"
NOTE: the query above needs to be changed to handle parameter binding / prepared statements. Since I don't know your database flavor, I've given you the basic query structure. Also, you should SELECT the specific columns you need from your table, not SELECT * (which is a performance hit).

Categories