How can I stop an empty SQL query from displaying all results? - php

I am creating a meat packaging search form, users can search for different packages using multiple forms and dropdown boxes. I have a had a lot of problems but most of it is sorted now, I only need to create an "Any" search for the dropdown boxes and the problem of empty textboxes displaying all results.
Currently when a user sends a search, they may have entered in some other text boxes, but when one of the forms is left empty that automatically displays all of the results. I want it so when a search is sent and a box is empty, the code ignores that form and just checks the ones that have info inside of them.
here is my test code (not my current final form code):
<body>
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("delyn_db", $con);
if (!$con)
{
die("Could not connect: " . mysql_error());
}
$descrip = mysql_real_escape_string($_POST['descrip']);
$sql = "SELECT * FROM delyn WHERE description LIKE '%" . $descrip . "%'";
$r_query = mysql_query($sql);
if ($descrip === "")
{
echo 'Null value';
}
while ($row = mysql_fetch_array($r_query))
{
echo '<br /> Description: ' . $row['description'];
}
?>
</body>
Anyone have any ideas on how to stop this?
EDIT: Sorry here is my HTML with the search boxes. The above php is just where the values are sent.
<body>
<form action="form5null.php" method="post">
<label for="description">Description:</label> <input type="text" name="descrip">
<br>
<label for="trayheight">Trayheight:</label> <input type="text" name="height">
<br>
<label for="traywidth">Traywidth:</label> <input type="text" name="width">
<br>
<label for="traydepth">Traydepth:</label> <input type="text" name="depth">
<br>
<label for="trayrange">Trayrange:</label> <select name="trayrange">
<option value="BBQ">
BBQ
</option>
<option value="Dessert">
Dessert
</option>
<option value="Display">
Display
</option>
<option value="Meat">
Meat
</option>
<option value="Microwave">
Microwave
</option>
<option value="Party">
Party
</option>
<option value="Salad/Wet Pasta">
Salad/Wet Pasta
</option>
<option value="Snacks">
Snacks
</option>
<option value="Standard">
Standard
</option>
</select> <label for="traytype">Traytype:</label> <select name="traytype">
<option value="Open">
Open
</option>
<option value="Cavitised">
Cavitised
</option>
<option value="Lid">
Lid
</option>
<option value="Tray">
Tray
</option>
<option value="Coallition">
Coallition
</option>
<option value="Bowl">
Bowl
</option>
<option value="Hinge pack">
Open
</option>
<option value="Pot">
Pot
</option>
<option value="Base & Lid">
Base and Lid
</option>
<option value="Rectangular">
Rectangular
</option>
<option value="Specalist">
Specialist
</option>
</select>
<br>
<label for="trayshape">Trayshape:</label> <select name="trayshape">
<option value="Rectangular">
Rectangular
</option>
<option value="Oval">
Oval
</option>
<option value="Square">
Square
</option>
<option value="Insert">
Insert
</option>
<option value="Round">
Round
</option>
<option value="Open">
Open
</option>
</select>
<br />
<input type="submit" value="Submit">
</form>
</body>

Add the following as the first option to all your dropdowns:
<option value="*">All</option>
Then use the SQL I provided in your duplicate question here:
Make SQL ignore a specific search value if clicked in a dropdown?
Dirk Nachbar gave a good answer as well.

Have you tried limiting your SQL queries by just checking if the values are blank/null (whichever is appropriate for PHP) and just not running the query if nothing is filled in?
e.g. (pseudocode)
if(box1.HasText || box2.HasText || box3.HasText)
{
RunTheSqlForForm1();
}

Related

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
}

Trying to populate a dropdown box from sql query in php

I need to populate a dropdown list based on the user's first dropdown selection, but before i even get that far I am just trying to populate one with a preselected team to make sure I get that part right first. However with this code I get my first dropdown with the team names, but then next to it is an empty text field and I can't seem to get the second dropdown to appear and populate. I am a newbie to html and php, I am fairly sure I'm missing something easy. Any help would be greatly appreciated and please let me know if I can be more clear about my issue. Thanks.
<!DOCTYPE html>
<html>
<head><style>
</style></head>
<body>
<form>
<select name="teams">
<option value="Atlanta Hawks ">Atlanta Hawks</option>
<option value="Boston Celtics ">Boston Celtics</option>
<option value="Charlotte Bobcats ">Charlotte Bobcats</option>
<option value="Chicago Bulls ">Chicago Bulls</option>
<option value="Cleveland Cavaliers ">Cleveland Cavaliers</option>
<option value="Dallas Mavericks ">Dallas Mavericks</option>
<option value="Denver Nuggets">Denver Nuggets</option>
<option value="Detroit Pistons ">Detroit Pistons</option>
<option value="Golden State Warriors">Golden State Warriors</option>
<option value="Houston Rockets ">Houston Rockets </option>
<option value="Indiana Pacers ">Indiana Pacers </option>
<option value="LA Clippers ">LA Clippers</option>
<option value="LA Lakers ">LA Lakers</option>
<option value="Memphis Grizzlies ">Memphis Grizzlies</option>
<option value="Miami Heat">Miami Heat</option>
<option value="Milwaukee Bucks ">Milwaukee Bucks</option>
<option value="Minnesota Timberwolves ">Minnesota Timberwolves</option>
<option value="New Jersey Nets">New Jersey Nets</option>
<option value="New Orleans Hornets ">New Orleans Hornets</option>
<option value="New York Knicks ">New York Knicks</option>
<option value="Oklahoma City Thunder ">Oklahoma City Thunder</option>
<option value="Orlando Magic ">Orlando Magic</option>
<option value="Philadelphia Sixers ">Philadelphia Sixers </option>
<option value="Phoenix Suns ">Phoenix Suns</option>
<option value="Portland Trail Blazers ">Portland Trail Blazers</option>
<option value="Sacramento Kings ">Sacramento Kings</option>
<option value="San Antonio Spurs ">San Antonio Spurs</option>
<option value="Toronto Raptors ">Toronto Raptors</option>
<option value="Utah Jazz">Utah Jazz</option>
<option value="Washington Wizards ">Washington Wizards</option>
</select>
<input type="text" name="team">
<?php
$con=mysqli_connect("localhost","nbastakm_josh","ateam","nbastakm_Stats");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT fname, lname FROM PlayerRegSeason WHERE team='NYK' and year='2009'";
$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$playermenu = "
<p><label>Players</label></p>
<select name='players' id='players'>";
while($row=mysqli_fetch_array($result)){
$playermenu = "<option>".$row['lname']."</option>";
}
$playermenu = "</select>";
echo $playermenu;
mysqli_close($con);
?>
</form>
</body>
</html>
Use dot to concatenate strings:
while($row=mysqli_fetch_array($result)){
$playermenu .= "<option>".$row['lname']."</option>";
}
$playermenu .= "</select>";
it isn't possible to use client option without resending to server. you need:
ajax,
a second page (step 2 in wizard) were you can check the "teams" or
you can reload page with javascript after changing teams

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

force option from <select> drop down before submit form

I want the user to be forced to select any option in the drop down apart from the default "selected" option
here is my drop down menu code;
<form><label>Select Tank:</label>
<select class="text2" name="tank" id="mySelect">
<option value="0" selected="selected">Select your tank</option>
<option value="4"> Tank#1 </option>
<option value="9"> Tank#2 </option>
<option value="21"> Tank#3 </option>
<option value="34"> Tank#4 </option>
</select>
<input type="button" id="btncheck" value="Submit"/>
</form>
and here is my java;
$('#btncheck').click(function(){
if ($("#mySelect ")[0].selectedIndex <= 0) {
alert("Please select a tank from the menu!");
return false;
}
});
jsfiddle: http://jsfiddle.net/36JZL/41/
for some reason it validates correctly but form isnt submitted.
You can do it with jQuery on client side but its not a good option to validate things on client side.
PasteBin: http://jsbin.com/zer/1
<form id="myForm">
<label>Select Tank:</label><br />
<select class="text" name="tank" id="tankSelector">
<option value="All" selected="selected"> Select Tank </option>
<?QUERY HERE TO PULL AND LOOP FROM DATABASE?>
<option value="<?php echo $row->id; ?>"> <?php echo $row->description; ?> </option>
<? END LOOP ?>
</select>
<input type="submit">
</form>
<script>
$(function() {
$('#myForm').submit(function(e){
if($('#tankSelector').val() == 'All') {
alert('Select tank!');
e.preventDefault();
}
});
});
</script>
<label>Select Tank:</label><br />
<select class="text" id="seltank" name="tank">
<option value="All" selected="selected"> Select Tank </option>
</select>
in the client side click event of your submit button add some javascript to check the value of your drop down.
if(document.getElementById("seltank").value == "All")
{
//put some code to alert the user or show error
return false; //this should prevent your post
}
Similar post is here How do I cancel form submission in submit button onclick event?
Here's what I do:
<select class="text2" name="tank" id="mySelect">
<option></option>
<option value="4"> Tank#1 </option>
<option value="9"> Tank#2 </option>
<option value="21"> Tank#3 </option>
<option value="34"> Tank#4 </option>
</select>
If the user hits submit without making a selection, they will be prompted to select an option automatically. The limitation is that you don't get a pretty little "select an option" placeholder.
Maybe this can help. Im yet to find a stable answer
If using php:
$val = $_POST['select_input']; <--- works fine
or
$val = $request->select_input <---- can be problematic
On Html
<select id="select_input" name="select_input" >
<option value="0">Pending</option>
<option value="1">Approved</option>
<option value="0" selected>Pending</option>
</select>

JS showing field if dropdown selected

I am wanting to show a hidden field but only when an option is selected in the dropdown. It does not matter which option is selected but I need one to be selected.
Javascript:
<script type="text/javascript">
function Select(sel,id,nu){
document.getElementById(id).style.display=sel.selectedIndex==nu?'block':'none';
}
</script>
Selection:
<select name="options[1]" id="select_1"
class=" required-entry product-custom-option"
title="" onchange="opConfig.reloadPrice();displayCondition();Select(this,divShow,1)">
<option value="" >-- Please Select --</option>
<option value="1" price="0" >Perfect </option>
<option value="2" price="-35" >Excellent </option>
<option value="3" price="-105" >Good </option>
<option value="4" price="-140" >Poor </option>
<option value="5" price="-252" >Broken </option>
</select>
The above onchange will only work if the first item is selected, so I am unsure how to make it work for any item selected. Also, I know the divShow should have some ' around it but I don't know how to write it into the following php:
$extraParams .= ' onchange="opConfig.reloadPrice();displayCondition();Select(this,'."divShow".',1)"';
Div Box:
<div id="divShow" style="display:none;">
<?php echo $this->getPriceHtml($_product) ?></div>
You do have to display simple quote to make divShow a JS string. In PHP (and in most of common languages) you escape them with \:
$extraParams .= ' onchange="opConfig.reloadPrice();displayCondition();Select(this,\'divShow\',1)"';
Without these quotes, your JS would try to look for divShow variable.

Categories