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
Related
I'm trying to filter a mysql table of results using an HTML select dropdown box. I have the filter working but then I want to have the option to display 'all' again but all I get is a blank set of results. Then when I refresh, it keeps the $POST value, I'd like that to be reset so 'all' of my results would show as default?? Cheers!
$sql = "SELECT * FROM books";
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
} else if($catvalue == 'all'){
$sql = "SELECT * FROM books";
}
$rs_result = mysql_query ($sql);
Bellow my select filter form.
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="All" selected="selected">All</option>
<option value="Design">Design</option>
<option value="Photography">Photograpy</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
<option value="All" selected="selected">All</option>
You have used "All" with an uppercase "A". PHP is case sensitive so your php code should be like this:
if(isset($_POST['value']) and $_POST['value']!='All') {
$catvalue = addslashes($_POST['value']);
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
} else {
$sql = "SELECT * FROM books";
}
$rs_result = mysql_query ($sql);
$sql = "SELECT * FROM books";
if(isset($_POST['value']) and $_POST['value']!='All') {
$catvalue = addslashes($_POST['value']);
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
$rs_result = mysql_query ($sql);
Refreshing the page will resend the same request.
A way to avoid that is to use the "Post/Redirect/Get" pattern.
It's well explained there : http://en.wikipedia.org/wiki/Post/Redirect/Get
$_POST['value'] always have a value on your code.
you may use the condition
if ( $_POST['value'] === 'All' ) {// select all}
$sql = "SELECT * FROM books";
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
if($catvalue != "All")
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
$rs_result = mysql_query ($sql);
First of all, you are writing inline queries which is not a safe way to work. This can lead to SQL injection. Bind the parameters and pass them safely in to the query.
As far as you logic is concerned, you will have to do this
$sql = "SELECT * FROM books ";// should always fetch all the books
if(isset($_POST['value'])) {
$catvalue = $_POST['value'];
if($catvalue != 'All') // if value is not "all", filter it
$sql = "SELECT * FROM books WHERE category = '$catvalue'";
}
I have a form with a select field:
<select class="indexSearchLocationList" name="locationList">
<option value="allLocations">Anywhere in London</option>
<option value="barking_and_dagenham">Barking and Dagenham </option>
<option value="barnet">Barnet</option>
What im trying to do is if the user chooses the option allocations (Anywhere in London) then I need to use that to select all when querying the database below is the php I currently have but how do I specifiy if that particular option is choosen:
$choosenLocation = $_POST['locationList'];
Just try this, if it is not meet your requirement, then add your requirement briefly as comment.
$choosenLocation = $_POST['locationList'];
if($choosenLocation == 'allLocations')
{
$query = "select * from TABLE ";
}
else
{
$query = "select * from TABLE WHERE condition="any_condition";
}
I think that may be
if(isset($_POST['locationList']) & $_POST['locationList']=='allLocations')
{
$query = "select * from TABLE ";
//based on the mysqli_ or PDO you execute
//fetch the row and display accordingly
}
Do you expect something similar,
$choosenLocation = $_POST['locationList'];
if(isset($choosenLocation) && $choosenLocation == 'allLocations'){
$query = "select * from TABLE ";
//based on the mysqli_ or PDO you execute
//fetch the row and display accordingly
}else{
$query = "select * from TABLE WHERE condition='your condition here' " ;
}
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' ";
}
Am facing troubles in this code, i just want to get all data from table row if the user selected "show all" from the select drop menu.
here is the select menu !
so, this menu grab data from this table, but if he selects All, what is the suitable code to echoing in between option value :)
<b>speciality:</b> <select id="main_mav" name="speciality">
<option value="none">Select speciality:</option>
<option value=""> All specialities </option>
<?php
$result = mysql_query('SELECT speciality FROM visits') or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['speciality'].'">'.$row['speciality'].'</option>';
}
?>
</select><br />
That's the Submit form !
if ($region=="All regions" ){
$region=$_POST['""'];
}
else ( $region=$_POST['region']);
$date1 =$_POST['from_date'];
$date2 = $_POST['to_date'];
$product=$_POST['product'];
$speciality=$_POST['speciality'];
$type=$_POST['visit_type'];
sql="SELECT id, customer_name, seller_1_name, seller_2_name FROM visits Where (speciality ='$speciality') AND (visit_type ='$type') AND (product ='$product') AND (region ='$region') AND (visit_date BETWEEN '$date1' AND '$date2')";
$result=mysql_query($sql); ## This line is new.
$num=mysql_numrows($result);
$row = mysql_fetch_array($result);
What's the correct code to enter if user selected " show all in drop menu " ?!
You really need to sanitize your inputs, at least with mysql_real_escape_string!
On to your actual question: just check if $speciality is empty, and generate a different query without the (speciality ='$speciality') condition.
Since your HTML referenced 'specialties' and your PHP referenced 'regions' I'm gonna just stick with 'regions', but here's the idea.
if ($region=="All regions" ){
$sql = 'SELECT id, customer_name, seller_1_name, seller_2_name, FROM visits';
} else {
$region = mysql_real_escape_string($_POST['region']);
$date1 = mysql_real_escape_string($_POST['from_date']);
$date2 = mysql_real_escape_string($_POST['to_date']);
$product = mysql_real_escape_string($_POST['product']);
$speciality = mysql_real_escape_string($_POST['speciality']);
$type = mysql_real_escape_string($_POST['visit_type']);
$sql = "SELECT id, customer_name, seller_1_name, seller_2_name FROM visits Where (speciality ='$speciality') AND (visit_type ='$type') AND (product ='$product') AND (region ='$region') AND (visit_date BETWEEN '$date1' AND '$date2')";
}
$result = mysql_query($sql); ## This line is new.
$num = mysql_numrows($result);
$row = mysql_fetch_array($result);
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.