I have three select box menus:
<select name="category" id="category" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
<select name="category2" id="category2" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
<select name="category3" id="category3" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
The selected options are sent with ajax to a server sided script. Here I catch the selected options and use them in MySQL queries:
$query = "
SELECT * FROM itemSparse
INNER JOIN item
ON item.id = itemSparse.id
LEFT JOIN itemsubtest
ON itemsubtest.subclass = item.Material
INNER JOIN itemModifiedAppearance
ON itemModifiedAppearance.ItemID = itemSparse.id
INNER JOIN ItemAppearance
ON ItemAppearance.identifier = itemModifiedAppearance.ItemAppearanceID
INNER JOIN manifestInterfaceData
ON manifestInterfaceData.ID = ItemAppearance.DefaultIconFileDataID
WHERE 1=1
";
$query.= " WHERE item.ClassID = 4 ";
if(isset($_POST["is_category"]))
{
$query .= " AND item.Material = '".$_POST["is_category"]."'";
}
if(isset($_POST["is_category2"]))
{
$query .= " AND itemSparse.OverallQualityID = '".$_POST["is_category2"]."'";
}
if(isset($_POST["is_category3"]))
{
$query .= " AND itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."'";
}
The problem:
The queries are only working when all three select menus have a selected value. If not all three menus have a selected option no results are shown.
I want that results are shown even if only one or two select menus have options selected. This means a query with an empty $_POST value should be ignored, but the others should be executed. How can I handle that?
The easiest way is to put WHERE 1=1 clause, that will result TRUE. After that you can append any AND clause.
$query = "SELECT * FROM table WHERE 1=1 "
if(isset($_POST["is_category"]))
{
$query .= " AND item.Material = '".$_POST["is_category"]."'";
}
if(isset($_POST["is_category2"]))
{
$query .= " AND itemSparse.OverallQualityID = '".$_POST["is_category2"]."'";
}
if(isset($_POST["is_category3"]))
{
$query .= " AND itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."'";
}
Also change this to use prepared statement, otherwise the query is vulnerable to SQL Injection attack
The issue you have is that the $_POST variables are all sent, because they are all part of the same form, so the resulting query has all the conditions with ='' for every field that is empty.
So you if you use !empty() instead of isset() your code should work
if(!empty($_POST["is_category"]))
{
$query .= "item.Material = '".$_POST["is_category"]."' AND ";
}
if(!empty($_POST["is_category2"]))
{
$query .= "itemSparse.OverallQualityID = '".$_POST["is_category2"]."' AND ";
}
if(!empty($_POST["is_category3"]))
{
$query .= "itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."' AND ";
}
However, do note that your query has a major sql injection vulnerability, so such code should not be used in a production environment. For a production server you need to use prepared statement.
Related
I have this drop down:
<select class="w-select filterdropdown" id="Tipo-de-cocina" name="tipofiltro" data-name="Tipo de cocina">
<?php
if (isset($_GET['tipofiltro'])) {
echo '<option value="' .$filtrocuisine. '"> ' .$filtrocuisine. "</option>";
} else {
echo '<option value="Todos los tipos">Todos los tipos</option>';
}
?>
<option value="Japonesa">Japonesa</option>
<option value="Mexicana">Mexicana</option>
<option value="India">India</option>
<option value="Mediterranea">Mediterranea</option>
<option value="Italiana">Italiana</option>
<option value="Americana">Americana</option>
<option value="Asiatica">Asiatica</option>
<option value="Thai">Thai</option>
<option value="China">China</option>
<option value="Francesa">Francesa</option>
<option value="Turca">Turca</option>
<option value="Latina">Latina</option>
<option value="Africana">Africana</option>
<option value="Griega">Griega</option>
<option value="Arabe">Arabe</option>
</select>
How can i make that when the user selects the field "Todos los tipos" my sql query returns all types? This is the sql behind:
if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
$filtroprecio = $_GET['preciofiltro'];
$filtrocuisine = $_GET['tipofiltro'];
$sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID
FROM Meals
INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID
WHERE Cooks.Area = '$area'
AND Meals.Capacity > 0
AND Meals.Price < '$filtroprecio'
AND Meals.Type = '$filtrocuisine'";
$result = mysqli_query($conn, $sql);
Basically I would need something such as "AND Meals.Type = any"
Cheers!
Well there are simpler methods but without rewriting everything the simple answer is that if the user selects Todos los tipos from the dropdown what you actually want to do is remove this selection criteria AND Meals.Type = '$filtrocuisine' from the query completely i.e. you no longer limit the query with that criteria.
So change your script like this :-
I am of course assuming that you have taken data from the $_GET array, validated it, and cleansed it before we get to this code.
if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
$filtroprecio = $_GET['preciofiltro'];
$filtrocuisine = $_GET['tipofiltro'];
$sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID
FROM Meals
INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID
WHERE Cooks.Area = '$area'
AND Meals.Capacity > 0
AND Meals.Price < '$filtroprecio'";
if ( isset($filtrocuisine) && $filtrocuisine == 'Todos los tipos' ) {
$sql .= " AND Meals.Type = '$filtrocuisine'";
}
$result = mysqli_query($conn, $sql);
I am trying to search in MySql db based on user input something like below.
User may/not select from the below fields
<select name="field_one" id="f1">
<option value="AA">AA</option>
<option value="BB">BB</option>
<option value="CC">CC</option>
</select>
<select name="field_two" id="f2">
<option value="11">11</option>
<option value="22">22</option>
<option value="33">33</option>
</select>
if User selects only 'field_one', then mysql_query should filter only based on 'field_one'. In this case there can be four combination
Filed_one is slected and filed_two is not selected
Field_One is not selected and field_two is selected
Filed_one is not selected and Filed_two is not selected
Field_one is selected and Field_Two is selected
What is the best and efficient methode to make this search?
I tried with 'case .... break;' and 'if', but when the first condition is met, code stops and does not check the next conditions
Can any one give me a clue? Thanks in advance for the help....
try this:-
$query = "select * from table_name where 1 ";
if(!empty($_POST['field1']) ) {
$query .= " AND field1 like '".trim($_POST['field1'])."'";
}
if(!empty($_POST['field2'])) {
$query .= " AND field2 like '".trim($_POST['field2'])."'";
}
// and so on
$result = mysql_query($query);
please use escape string also http://php.net/mysql_real_escape_string
<?php
$sql = "SELECT * FROM table_name WHERE 1";
if(isset($_POST)){
if(isset($_POST['field_one'])){
$sql.= 'AND field_one'= $_POST['field_one'];
}
if(isset($_POST['field_two'])){
$sql.= 'AND field_two'= $_POST['field_two'];
}
}
mysql_query($sql);
?>
Example, not tested and needs lots of variable processing against SQL injection
$where = "";
$bits = array();
$bitset=false;
if(isset($_POST['field_one') && strlen($_POST['field_one')) > 0)
{
$bitset = true;
$bits[] = " field1 = $_POST['field_one')"
}
if(isset($_POST['field_two') && strlen($_POST['field_two')) > 0)
{
$bitset = true;
$bits[] = " field2 = $_POST['field_two')"
}
if($bitset)
{
$where = implode(", " $bits);
}
$sql = "select * from table " . $where;
You can also use PDO & param binding to avoid SQL Injection : http://www.php.net/manual/fr/pdostatement.bindparam.php
So here's my php code:
$sql1 = "SELECT year FROM reports ORDER BY year DESC";
$res1 = mysql_query($sql1);
while($row = mysql_fetch_array($res1)) {
$selectYear = "
<select id='select_year'>
<option value='".$row['year']."'>".$row['year']."</option>
</select>
";
}
What I want it to do is just output one year instead of what its doing now which is outputting every single year and there is one entry for each month of the year so there are 12 entries with the same year so my html is this:
<select id='select_year'>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
But this is what I actually want:
<select id='select_year'>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
This is to sort through all the results by year so that the user can just use the select to select which year they want to view.
There are lots of ways of doing this, but the easiest is probably:
$sql1 = "SELECT DISTINCT year FROM reports ORDER BY year DESC";
With DISTINCT, the database will only return one of each value. Then you don't have to waste any resources processing data on the PHP side.
#Thomas Kelley has given the perfect answer above.
However, if you insist on PHP solution. You can do it as follows.
$res1 = mysql_query($sql1);
$placeHolder = ",";
while($row = mysql_fetch_array($res1)) {
if ( strpos($placeHolder , $row['year']) )
continue;
$placeHolder .= $row['year'] .',';
$selectYear = "
<select id='select_year'>
<option value='".$row['year']."'>".$row['year']."</option>
</select>
";
}
I faced a problem in developing advanced search code using php as an input and output, sql to select and filter data ..
php code:
<form action="index.php?Type=Advance" method="post">
<input type="text" name="name">
<input type="text" name="sponsor">
<select size="1" name="gender" id="">
<option value="male">male</option>
<option value="female">female</femal>
</select>
<select size="1" name="address" id="">
<option value="x">x</option>
<option value="y">y</option>
<option value="z">z</option>
</select>
<input type="submit">
</form>
Then i declare the variables
public function AdvanceSearch($name,$sponsor,$gender,$address)
{
$cheack = "";
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
}
if(isset($sponsor)&&$sponsor != ""){
$cheack.=" AND sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
$cheack.=" AND gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
$cheack.=" AND workplace = '$address' ";
}
$DB = mysql_query("SELECT * FROM table WHERE 1 = 1 ".$cheack);
echo "SELECT * FROM user WHERE ".$WHQ;
exit();
actually it works, however if i didn't insert the name ... the sql statement will be like this
SELECT *
FROM table
WHERE AND sponsor = 'www'
AND gender = 'male'
what if i want to search on the table but without inserting the name .. how can i let the sql statement works if i didn't inset the name.
A typical solution to this is always adding a true condition first, such as 1=1. The query without any extra conditions then becomes
SELECT * FROM table WHERE 1=1
and when you add any AND conditions you can just add them to the end, with no special case for the first or last condition:
SELECT * FROM table WHERE 1=1 AND sponsor = 'www' AND gender = 'male'
Note that if you used OR instead of AND the first condition should be false, like 0=1.
You can use a flag variable like :
$cheack = "";
$flag = False;
if(isset($name)&&$name != ""){
$cheack.=" name = '$name' ";
$flag =True;
}
if(isset($sponsor)&&$sponsor != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="sponsor = '$sponsor' ";
}
if(isset($gender)&&$gender != ""){
if($flag){
$cheack.="AND ";
}
$cheack.="gender = '$gender' ";
}
if(isset($address) &&$address != "" ){
if($flag){
$cheack.="AND ";
}
$cheack.="workplace = '$address' ";
}
table (book) ==> (keyid,name)
<form action="se.php">
<select>
<option value="1">book1</option>
<option value="2">book2</option>
<option value="3">book3</option>
<option value="????">All Book</option>
</select>
<input type="submit" name="search" value="search">
</form>
//se.php
$keyid=$_GET[keyid];
$sql=mysql_query("SELECT `name` FROM `book` WHERE `keyid`='$keyid'");
//end page
what i put in last option value (????) for sql query search all content???
all
then:
$where = '';
if $keyid != all then {
$where = WHERE `keyid`= $keyid // escape value protect from sql injection!
}
mysql_query("SELECT `name` FROM `book` $where");
This should do it:
$keyid=mysql_real_escape_string($_GET[keyid]);
if(trim($keyid)!="")
$where = " `keyid`='$keyid' ";
else
$where = " 1 ";
$sql=mysql_query("SELECT `name` FROM `book` WHERE $where ");
Your code is very weak about protecting from sql injection. You should escape your inputs and never trust the values that you receive. Think about this value in your option:
<option value="';truncate table book;">All Book</option>
A good approach is the answer by #cojack