I'm coding a feature in PHP, it's a search engine.
<form action="result" method="POST">
<select name="instrument" id="instrument">
<option value="all">All instrument</option>
<option value="1">Guitar</option>
<option value="2">Bass</option>
<option value="3">Battery</option>
<option value="4">Singer</option>
</select>
<select name="theme" id="theme">
<option value="all">All themes</option>
<option value="1">Metal</option>
<option value="2">Jazz</option>
<option value="3">Rock</option>
<option value="4">Blues</option>
</select>
<input type="submit" value="search" />
</form>
I already code this search engine like this and it works
<?php
if(isset($_POST)) {
$theme = $_POST['theme'];
$instrument = $_POST['instrument'];
$req_search = $bdd->query("SELECT * FROM user,theme,instrument WHERE theme.theme_id = user.user_theme AND instrument.instrument_id = user.user_instrument AND theme_id =".$theme." AND instrument_id =".$instrument);
if($req_search->rowCount()>0) {
while($search = $req_search->fetch()) {
?>
<p><?php echo $search['user_username']; ?></p>
<?php
}
$req_search->closeCursor();
} else {
echo "Users not found";
}
}
?>
You can find users who is matching with those options (without All instrument and All themes.
Everything is stored into a MySql database.
However when I click on All themes and All instrument. I want to update my select request. Like if I select All instrument and All themes I want to display every users. Or if I select All instrument and Metal, I want to display all users listening to metal and playing whatever instrument.
Thanks for your help !
You can construct your query to be conditional depending on whether $theme and $instrument have values:
$query = "SELECT * FROM user,theme,instrument
WHERE theme.theme_id = user.user_theme
AND instrument.instrument_id = user.user_instrument".
($theme!="" ? " AND theme_id='$theme'" : "").
($instrument!="" ? " AND instrument_id='$instrument'" : "");
$req_search = $bdd->query($query);
That said, you should look into PDO Prepared Statements and Placeholders, because all this would take is someone to fiddle around with the DOM to perform some MySQL Injection.
Related
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.
Hi I want to filter my searches in the sql based on the requirement the user wants so i used a select tag and depending on the value of the select tag a certain sql statement will be used but its not working as expected can you help me looked what went wrong here:
$strFilterByStatus = $_POST['byStatus'];
<select name="byStatus" id="byStatus" onChange="frmAdminWorklist.submit()">
<option value="all">All</option>
<option value="recovered">Recovered</option>
<option value="unrecovered">Unrecovered</option>
</select>
<?php
if($strFilterByStatus=='all'){
$strSQL = "SELECT * FROM tblcase";
$SQL=mysql_query($strSQL);
}
?>
appreciate the help :)
Suppose this is all in theTest.php
<?php
$strFilterByStatus = $_POST['byStatus'];
?>
<form id='testform" action="theTest.php" method="post">
<select name="byStatus" id="byStatus" onChange="frmAdminWorklist.submit()">
<option value="all">All</option>
<option value="recovered">Recovered</option>
<option value="unrecovered">Unrecovered</option>
</select>
<input type='submit' name='' value='Go test it'>
</form>
<?php
if ( $strFilterByStatus == 'all' )
{
$strSQL = "SELECT * FROM tblcase";
$SQL = mysql_query($strSQL);
}
?>
So I am currently having some difficulty using PHP to populate a select option on an HTML form. I need to have the select options filled with the data from my sql table and then I need to populate the selections into a different table in sql. First I will desribe the sql table that I am using. This is my first time using PHP and SQL so please keep that in mind if the code is completely off.
Note, I am able to connect to my database without any issues
SQL Data:
Table Name = "All Animals"
Column Name = "Group"
PHP Code:
$query = "SELECT *, dbo.All Animal.Group as allAnimal_Group
LEFT JOIN dbo.All Animal on dbo.Response.animalGroup = dbo.All Animal.Group
WHERE dbo.Response.animalGroup = %s";
$db->query($query, $Group);
$r = $db->fetch();
HTML and PHP Code:
<p>
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option></select></p>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
Thank you for looking and helping, I appreciate the assistance!
Your drop down list is closed before the php code. So edit it as below first.
<p>
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
</select></p>
For the second part of your question, put this code inside html form and submit it to the server once the selection is made. So the complete code will be
<p>
<form action="your_file_name.php" method="post">
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
</select>
<input type="submit" name="submitBttn" value="Submit">
</form></p>
in your_file_name.php file, write this to retrieve what is selected as,
$_POST['Group']
Then you can write sql code like "INSERT INTO table_name (column_name) VALUES ($_POST['Group'])"
More on html forms read this... http://php.net/manual/en/tutorial.forms.php
Update your query to use LIKE instead of = sign for wild character matching
$query = "SELECT *, dbo.'All Animals'.Group as allAnimal_Group
FROM dbo.'All Animals'
LEFT JOIN dbo.'All Animals' on dbo.Response.animalGroup = dbo.'All Animals'.Group
WHERE dbo.Response.animalGroup LIKE '%s'";
P.S You should change the foreach to use $r as iterator because you are storing database result in $r and not in $Group
foreach($r as $m){
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am totally new to scripting, basically i have to try and finish a school project on a coaching tour project. The idea is to allow customers to register and book a tour.
What i am having problem with is, i have no idea on how to create a dynamic drop down list where the booking form will take the data from mysql database.
Lets say for example :
The customer needs to select a choice of tour i.e (industrial, cultural, military) from the first drop down list.
After selecting a tour, the next drop down list should list the destinations i.e. (UK, France, Germany, etc) dependant on the above (tour) choice.
Then the third list should show the start dates dependant on the above (destination) choice.
All the data in the drop down list should come from the database. Also when the customer submits the form, all those data should go into the customers booking table in the database.
I was told that javascript should be the answer, but i have searched so many forums and look at tutorials which they are all confusing. Hence I came to ask here! Any help on how to do this is much appreciated. Thnx!
Below is the code of how i only know how to do this:
<h2><center>PLEASE PLACE YOUR BOOKING</center></h2>
<form action="booking.php" method="post">
<table width="700 border="0" align="center" cellpadding="0" cellspacing="0">
<tr><td width="210" height="45">Tour Type:</td><td>
<select name="tour_type">
<option value="Cultural">Cultural</option>
<option value="Industrial">Industrial</option>
<option value="Military">Military</option>
</select></td></tr>
<tr><td width="210" height="45">Duration:</td><td>
<select name="duration" >
<option value="1_Day">1_Day</option>
<option value="7_Days">7_Days</option>
<option value="14_Days">14_Days</option>
</select></td></tr>
<tr><td width="210" height="45">Destination:</td><td>
<select name="destination" >
<option value="England">England</option>
<option value="Wales">Wales</option>
<option value="Scotland">Scotland</option>
<option value="France">France</option>
<option value="Belgium">Belgium</option>
<option value="Germany">Germany</option>
</select></td></tr>
<tr><td width="210" height="45">No. of Passengers:</td><td>
<select name="no_of_passengers" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select></td></tr>
<tr><td width="210" height="45">Depature:</td><td>
<select name="departure" >
<option value="13 May 2013">13 May 2013</option>
<option value="28 May 2013">28 May 2013</option>
<option value="11 June 2013">11 June 2013</option>
<option value="26 June 2013">26 June 2013</option>
<option value="14 July 2013">14 July 2013</option>
<option value="27 July 2013">27 July 2013</option>
</select></td></tr>
<tr><td width="210" height="45"><input type="checkbox" name="accomodation"
value="YES"/>Accomodation</td></tr>
<tr><td width="210" height="45"><input type="checkbox" name="mailshot"
value="YES"/>Mailshot</td></tr>
<tr><td width="210" height="45"><input type="submit" name="submit" value="submit"></td></tr>
</table>
</form>
</html>
<?php
//When submit button is pressed.
if (isset($_POST['submit'])) {
//Include the server and database connection.
include('cn.php');
session_start();
//retrieve data input from booking form and make it equal to the variable ($)
$tour_type = $_POST['tour_type'];
$duration = $_POST['duration'];
$destination = $_POST['destination'];
$no_of_passengers = $_POST['no_of_passengers'];
$departure = $_POST['departure'];
// accomodation confirmation
if (isset($_POST['accomodation'] ))
{$accom = $_POST["accomodation"];
} else {
$accom = "NO";
}
// mailshot confirmation
if (isset($_POST['mailshot'] ))
{$mail = $_POST["mailshot"];
} else {
$mail = "NO";
}
$userUsername = $_SESSION['loggedInUser'];
// Build the SQL query to retreive the variables ($) and input the data into the database.
$sql = "INSERT INTO booking
(user_id,tour_type,duration,destination,no_of_passengers,departure,accomodation,mailshot)
VALUES ((SELECT user_id FROM user WHERE user_username = '" .
$userUsername . "'),'$tour_type','$duration','$destination',
'$no_of_passengers','$departure','$accom' ,'$mail')";
// test the sql statement.
if(!mysql_query($sql,$cn)) {
die(mysql_error($cn));
}
// direct to this page when booking is successful.
header('Location: booking_success.php');
}
?>
I had a similar issue. I found one guide that actually work and where he explains what he does. One thing that you should keep in mind when reading it though that it uses a different version of Jquery than the latest one, so there are a few differences in the syntax. These differences are minor though and can be found in the comments.
http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html
In your case it would look something like this:
SQL
Create three tables one called id(Integer), one called master_id(Integer) and one called names(varchar).
Id is going to go from 1->x (meaning the last row is number x).
master_id is going to be 0 for the items that is in the first drop down military etc. All of the items that you want to go in to the category military will have the same value of master_id as military has as id, for example 1. You follow this principal along with all the sub categories and dates. name is just a label...
Main site php/HTML
The Html would look something like this, where you put the script in the php in the head of your site.
?php
try {
$objDb = new PDO('mysql:host=localhost;dbname=tour', 'root', 'root');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `region`
WHERE `master_id` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
?>
This is the forms.
<select name="tour" id="tour" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="location" id="location" class="update"
disabled="disabled">
<option value="">----</option>
</select>
<select name="date" id="date" class="update"
disabled="disabled">
<option value="">----</option>
</select>
</form>
Remember to add the jquery and corect path to the ajax script.
PHP function
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {
$id = $_GET['id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=tour', 'root', 'password');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `categories`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
ajax.js - the script
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('func/tour_function.php', { id : id, value : v }, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">---- </option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').on('change', function() {
formObject.run($(this));
});
});
Just remember to get the paths right and to include Jquery 1.9.1 and it should work.
To point out an answer already on this site
Ajax approach to populating a second dynamic dropdown based on the selection in the first
Essentially, the short version would be an onchange event that loads data from your server
<select name="first_dropdown" onchange="$('#dropdown2_container').load('your_script.php?nid='+this.value);">
<option....
</select>
...
<div id="dropdown2_container" style="display:none"> </div>
I'm not a big fan of obtrusive javascript like this, but it's a start for you. If you want something a bit more elegant, try the following link.
http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
At least a bit of this should get you started.
There are a couple of approaches you can take. Since you are new to scripting, I would suggest avoiding AJAX at this point. You need something like the following:
On the server-side (PHP), output the data into JavaScript variables that you can work with. For example, you could store the data in an array.
Example: var tours = [{ id:1, name:"Tour#1" }, { id:2, name:"Tour#2" }, etc.]
You'll want to load all tour data, destination data, and start dates into the script, with enough information to link which child records belong to which parent records.
When the page first loads, the tour data should be populated into the first dropdown, but the second and third should be blank since they populate base on the previous ones.
When the user makes a change to a dropdown value (onchange event), then apply the logic to load the entries to the next dropdown based on the selection in the previous dropdown.
Example: <select id='tours' onchange='changetour();'></select>
You'll also want to handle the situation where the user clears out a selection (clear out all the child selections in that case), or the user goes back to the first dropdown and changes their selection after they've already selected something in the second and third.
This should give you a rough idea of an algorithm to get started. I would suggest giving your best effort on each item above, and come back with specific questions after you've tried writing a solution and get stuck with a specific problem.
Hello I am really struggling with this. I was asked to develop a script to calculate oil price but cannot get it to work. I have been able to setup a form to update fuel price.
I have a table called fuel_price. In this table will be cost per litre of fuel which is stored under Price. For example if oil price per litre is £0.50 I need to multiply this value by value selected within form dropdown.
Can anyone please guide me on what I am supposed to do??
Ok heres an update code preview.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="fueltype">
<option>- Select fuel type -</option>
<option value="Diesel">Diesel</option>
<option value="Red Diesel">Red Diesel</option>
<option value="Home Heating Oil">Home Heating Oil</option>
</select>
<select name="qtylitres">
<option>- Qty in Litres -</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="400">400</option>
<option value="500">500</option>
<option value="900">900</option>
<option value="1000">1000</option>
</select>
<input type="hidden" name="id" value="" />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include 'mysql_connect.php';
$pdo = '';
$stmt = $pdo->prepare("SELECT `Oil` from `fuel_price` WHERE id = '1'");
if (!$stmt->execute()) { die($stmt->errorInfo[2]); }
$row = $stmt->fetch();
$price = $row['Oil'];
echo $_POST['qtylitres'] * $price;
?>
Anyone know where I am going wrong??
Thanks
<?php
//Connect to database here. In this example, I'll assume you connected using PDO
//Although the same logic applies on any engine.
$stmt = $pdo->prepare("SELECT `price` from `fuel_price` WHERE `type` = :type"); //Prepare a query
$stmt->bindValue(':type', $_POST['type']); //Assuming the first <select> is named type
if (!$stmt->execute()) { die($stmt->errorInfo[2]); } //Display an error and terminate script if query failed.
$row = $stmt->fetch(); //Assuming you have only one row, fetch should only be called once.
$price = $row['price'];
echo $_POST['qtylitres'] * $price; //Multiply quantity with price and print result.
?>
Note that I have not tested it, but it should work. Your markup is incomplete, it lacks the opening for the first <select>. Read the comments and you should be good to go.
assuming that you have a column 'price' in your table, and that the only result contains the correct price:
include 'mysql_connect.php';
if (isset($_POST['submit'])) {
// edit: added fueltype in the where clause
$fueltype = mysql_real_escape_string($_POST['fueltype']);
$q = "SELECT * FROM fuel_price WHERE id = '1' AND fueltype='$fueltype'";
$result = mysql_query($q);
$row= mysql_fetch_array($result);
$price = $row['price'] * $_POST['qtylitres'];
echo $price;