I am writing a reservation system. On the main page I would give a choice of category, viewed the equipment available for booking.
For example I have code like this:
<select>
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
I wish that each choice was associated with a separate query to the database, and that was the result of a query dynamically displayed on the screen.
It would be great if you could show me some sample code.
Regards
$query = mysql_query("SELECT * FROM choices");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
If you need separate query for each choice the code doesns't change much:
$query = mysql_query("(SELECT * FROM choices) UNION (SELECT * FROM choices1) [etc]");
while($row=mysql_fetch_assoc($query)) {
echo '<option value="'.$row['value'].'">'.$row['value'].'</option>';
}
There are two parts to your question; 1 - Detecting which query to run and 2 - Displaying the results dynamically.
Part 1: Detecting which query to run:
Given hard-coded choices and no parameters for the query, using your above code, you can determine which query to run using the following:
For the HTML part, as part of a form, create the select as you did above (but with a name)
<select name="querySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
And in the PHP:
$querySelect = $_GET['querySelect'];
switch($querySelect)
{
case 'a':
$sql = "SELECT * FROM TableA";
break;
case 'b':
$sql = "SELECT * FROM TableB";
break;
}
$results = mysql_query($sql);
Part 2: Displaying the results dynamically
With the $results, what you do with the data very much depends on what you want to achieve. At a very basic level, you can do the following to dynamically display a table of the results:
if(mysql_num_rows($results) > 0)
{
$header = false;
print "<table>"
while($row = mysql_fetch_assoc($results))
{
if(!$header)
{
$headings = array_keys($row);
print "<tr>";
for($i=0;$i<count($headings);$i++)
{
print "<th>".htmlspecialchars($headings[$i])."</th>";
}
print "</tr>";
$header = true;
}
print "<tr>";
foreach($row as $value)
{
print "<td>".htmlspecialchars($value)."</td>";
}
print "</tr>";
}
print "</table>"
}
else print "<h1>No Results Found!</h1>";
mysql_free_result($results);
There is still alot not covered in my answer because I can't say what level of detail is required. You will also need to cover things like your connection to MySQL, error handling, formatting of the table...
Update
Hmmm, very interested to know why this has been downvoted. If someone can please explain in comments where I have misinterpreted the question or misguided the user, I would appreciate it.
If you use jQuery the code might look like
<select id="select_id">
<option value = "a">A</option>
<option value = "b">B</option>
<option value = "c">C</option>
<option value = "d">D</option>
<option value = "e">E</option>
</select>
<script type="text/javascript">
$('#select_id').change(function(e) {
// this code send selected value to the server
$.post('url', {selected_value: this.value}, function(response) {
// handle the server's response
});
});
</script>
On server side take the value from $_POST and make a query. And remember - do not trust to data from client-side. You never know who is over there. Always check incoming data and DO NOT use such constructions
$sql = "SELECT * FROM table_name WHERE name = '{$_POST['selected_value']}'";
because there might be any string including those can drop all databases, clear data and so forth.
Related
I'm working on a complex project for a car dealership where I have to create database search based on multiple criteria. The cars in the database are divided into 3 types - let's call them A, B and C. Let's say that the value of A=1, B=2, C=3. The url would look something like index.php?type_id=1 . The working search code so far is as follows.
In index.php :
<script type="text/javascript">
$(document).ready(function(){
$('#car').on('change',function(){
var carID = $(this).val();
if(carID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'marque_id='+carID,
success:function(html){
$('#model').removeAttr("disabled");
$('#model').html(html);
}
});
}else{
$('#model').attr("disabled");
$('#energy').attr("disabled");
}
});
});
</script>
$type_id = $_GET['type_id];
$query = $db->query("SELECT DISTINCT marque_name,a.marque_id FROM vehicule_marque as a INNER JOIN vehicule as b WHERE b.type_id = '$type_id' AND a.marque_id = b.marque_id order by marque_name");
$rowCount = $query->num_rows;
<div>Select car</div>
<select name="car" id="car" required >
<option value="">Select Car</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['marque_id'].'">'.$row['marque_name'].'</option>';
}
}else{
echo '<option value="">Car not available</option>';
}
?>
</select>
<div>Select car model</div>
<select name="model" id="model" disabled>
<option value=""><!--Select car first--></option>
</select>
In ajaxData.php :
if(isset($_POST["marque_id"]) && !empty($_POST["marque_id"])) {
//Get all state data
$query = $db->query("SELECT DISTINCT a.modele_id, modele_name, a.marque_id FROM vehicule_modele as a INNER JOIN vehicule as b WHERE a.marque_id = ".$_POST['marque_id']." AND b.type_id = '$type_id' AND b.marque_id = a.marque_id AND b.modele_id = a.modele_id ORDER BY modele_name ");
//Count total number of rows
$rowCount = $query->num_rows;
//Display model list
if($rowCount > 0){
echo '<option value="">Select model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['modele_id'].'">'.$row['modele_name'].'</option>';
}
}else{
echo '<option value="">Model not available</option>';
}
}
The problem is with taking the type_id value and using it in ajaxData.php query in order to show the model once the customer selected a car brand. In index.php, I GET the value from the url successfully (I tried echoing it and it worked), but then I can't get it to work in the other query - it keeps on showing only "Model not available" option. I tried putting inside the script the $type_id into a new variable, but this didn't work either. I'm not sure what I'm missing. If I remove the type_id condition, everything works perfectly. If anyone has any idea how to fix this, I would appreciate it.
First of all, you need to understand that request to url index.php?type_id=1 and request to url ajaxData.php are different requests and know nothing about each other.
So, if you try to access $_GET['type_id'] in ajaxData.php you will obviously receive nothing, because $_GET is empty in ajaxData.php. If you send request to ajaxData.php?type_id=42 you will get 42 as $_GET['type_id'].
So, you if you want to use some $_GET or $_POST data in ajaxData.php you must send this data explicitly.
It can be either:
url:'ajaxData.php?type_id=' + yourValue,
// access it with $_GET['type_id']
or
data:'marque_id='+carID+'&type_id='+yourValue,
// access it with $_POST['type_id']
I have a list box and have 2 questions.
1st how can i still have the text to say Select a country?
2nd on my update page it displays the proper country but will not allow it to be change for it will not list any of the other countries in edit page
<?php
$sql = "SELECT countries.country_id, countries.country_name, users.user_country FROM countries, users
WHERE users.user_country = countries.country_id";
$result = query($sql);
?>
<select class="form-control input-lg box" id="country" name="country">
<?php
$i = 0;
while (($row = mysqli_fetch_assoc($result)) != false) {
?>
<option value="<?=$row["country_id"];?>"><?=$row["country_name"];?></option>
<?php
$i ++;
}
?>
Well, to have a default option not provided by your database call, you just need an HTML statement such as
<option value="">Select a country</option>
right below your <select> statement.
And we can't see your table definitions, but your SQL code seems to be picking the specific country that the user is associated with, so that there is only one country in the list. You probably need two queries: One that obtains the user's current country, and a second that obtains the entire list of countries.
After the first query, save the user's current countryid in a variable - say, $usercountryID.
Then, in your loop through the countries, compare each countryID to the user's country, like this:
while (($row = mysqli_fetch_assoc($result)) != false) {
if ($usercountryID == $row["country_id"]) $selected = " selected";
else $selected = "";
echo "<option value='{$row['country_id']}$selected>{$row['country_name']}</option>\n";
}
$selected could be defined many ways, of course, including in a conditional assignment statement. I omitted the $i counter, which isn't needed here, but, of course, you might need it later.
Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.
You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....
Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic
I have a HTML etc.. tags now what I want to achieve is upon a selection of ie. i want to load the related info from database to in a new tag with as many tags.
I am using PHP to do achieve this now at this point if for example i choose option1 then the query behind it retrieves relevant information and stores it in a array, and if I select option2 exactly the same is done.
The next step I made is to create a loop to display the results from array() but I am struggling to come up with the right solution to echo retrieved data into etc. As its not my strongest side.
Hope you understand what I am trying to achieve the below code will clear thing out.
HTML:
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP:
$form = Array();
if(isset($_POST['workshop'])){
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
while($result2 = mysqli_fetch_assoc($query2)){
//The problem I am having is here :/
echo "<select id='Forex' name='Forex' style='display: none'>";
echo "<option value='oko'>.$result[1].</option>";
echo "</select>";
print_r($result2);echo '</br>';
}
}else{
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%'";
$query = mysqli_query($link, $sql);
while($result = mysqli_fetch_assoc($query)){
print_r($result);echo '</br>';
}
}
}
Try this code:
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value='oko'>{$result['course']}</option>";
}
echo "</select>";
echo '</br>';
From the top in your php:
// not seeing uses of the $form I removed it from my answer
if(isset($_POST['workshop'])){
$workshop = $_POST['workshop'];
$lowerWorkshop = strtolower($workshop);
// neither of $_POST['Forex'] nor $_POST['Binary'] are defined in your POST. you could as well remove those lines?
//Retrieve Binary Workshops HERE we can define the sql in a single line:
$sql = "SELECT id, course, location FROM courses WHERE course LIKE '%$workshop%' OR course LIKE '&$lowerWorkhop%'";
$query = mysqli_query($link, $sql); // here no need to have two results
// Here lets build our select first, we'll echo it later.
$select = '<select id="$workshop" name="$workshop" style="display: none">';
while($result = mysqli_fetch_assoc($query)){
$select.= '<option value="' . $result['id'] . '">' . $result['course'] . '</option>';
// here I replaced the outer containing quotes around the html by single quotes.
// since you use _fetch_assoc the resulting array will have stroing keys.
// to retrieve them, you have to use quotes around the key, hence the change
}
$select.= '</select>';
}
echo $vSelect;
this will output a select containing one option for each row returned by either of the queries. by the way this particular exemple won't echo anything on screen (since your select display's set to none). but see the source code to retrieve the exemple.
I can't seem to get the value for a 'selected item' to pass to a JavaScript function with PHP that uses the value to query data from MySQL database -> populates a different drop down list.
Here is my 'HTML' code
<select name="numbers" id="numbers" onChange="populateOtherSelect()">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
</select>
<?php echo $option ?>
Here is my 'JavaScript' function code
function populateOtherSelect() {
<?php
// code that opens db connection
$numbers = $_POST['numbers'];
$query = "select*from Database.Table where Something = 'Something' and Numbers like '%".$numbers."%'";
$result = mysql_query($query);
$option = "";
while($row = mysql_fetch_array($result))
{
$OtherOptions = $row["OtherOptions"];
$option.="<option value=\"$OtherOptions\">".$OtherOptions."</option>\r\n";
}
// code that closes db connection
?>
}
Any information will be helpful.
Thanks very much
It seems your javascript code is part of the html / php document and that´s not going to work; the php is run only at initial page-load and at that moment there probably is no $_POST variable.
What you need to do, is make an ajax call to a php script at the moment your first select is changed and use the response from that ajax call to populate your second select.
So basically your javascript function would have to look like:
function populateOtherSelect() {
/*
* 1. get the value of the numbers select
* 2. make an ajax call to a php script / the server that gets some information from a database
* 3. use the response from the ajax call to populate your second select
*/
}
I think you need to add a space in your select statement:
$query = "select * from Database.Table where Something = 'Something' and Numbers like '%".$Numbers."%'";
First of all, the $Numbers variable doesn't exist, it's $numbers.