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
Related
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.
MY HTML
<div class="normal-text">
<? $check = mysql_query("SELECT * FROM client")or die(mysql_error());
while ($check2 = mysql_fetch_array( $check ))
{
$checkgather = mysql_query("SELECT * FROM gather where client_id = '".$check2['client_id']."' ")or die(mysql_error());
$checkgather2 = mysql_fetch_array( $checkgather );
echo $check2['client_name'].' :
<select name="gather" class=\"form-field\">
<option value="hashtag" '.(($checkgather2['gather_choice']=='hashtag')?'selected="selected"':"").' >hashtag</option>
<option value="latitude" '.(($checkgather2['gather_choice']=='latitude')?'selected="selected"':"").' >latitude/longitude</option>
<option value="followers" '.(($checkgather2['gather_choice']=='followers')?'selected="selected"':"").'>followers</option>
</select>
Start Thread to gather<br>';
}
?>
<br>
<input class="submit-button" type="submit" name="submit" value="Update" />
</div>
I have several rows of results.. each with a dropdown menu of what's in the DB... If I change 1 or multiple values, and I press the UPDATE button... How can I treat the code..
I'm assuming I'll need a foreach(.... )
my current PHP is this:
if (isset($_POST['submit']))
{
$update = mysql_query("UPDATE gather set gather_choice = ' ' where client_id = ' ' ")or die(mysql_error());
}
But I'll probably need a foreach somewhere... Any tips on how to make this work?
thanks
You can do this, assuming you have a unique key on client_id
INSERT INTO gather (gather_choice, client_id)
VALUES (first_choice, first_client_id), (second_choice, second_client_id)
ON DUPLICATE KEY UPDATE client_id = VALUES(client_id)
This will basically try to insert first, but seeing that it already exists, will just update it.
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
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' ";
}
I have several drop lists where if no option is selected then the value is = ""...
I cant figure out how to build the query for mysql in PHP.
query = SELECT * FROM db
I assume you have a select like this:
<select name="data[]" multiple="multiple">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
Your php can be something like
<?php
$data = array();
$data = $_POST['data'];
$query = "select * from table";
if (count($data > 0)) {
for ($i = 0; $i < count($data); $i++) {
$data[$i] = "'{$data[$i]}'";
}
$query .= " where field in (".implode(",", $data).")";
}
Too less information, but here's what I would do
$rows = $db->query(
'select *
from
table
where
checkbox_value = ?',
$_POST['checkbox']
);
In $rows you will have all the data you need.
You can run a SELECT on a table not on a DB! A Database consists of many tables. See http://www.php.net/manual/en/function.mysql-select-db.php
Check out w3Schools sql tutorials.
Or more specifically the select tutorial
Also the PHP/mysql tutorial will give you all that you need for this stuff.