Getting a value from url and using it in sql query - php

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']

Related

Join Function used to match value of field in one table with other table

I am trying to display field values, when values of field in the table matches with the values in field of another table.
Its like I am creating a drop down fields. Here basis the car Model dropdown. Like Ferrari as Model chosen in dropdown by user as prod_name under table newcar_products then its variants like Portnifo, superfast,488 should be shown under Variant field.
But whats happening as of now - irrespective of model selected whether Ferrari or Honda or Volkswagen - the variants displays the entire list of variants like polo, jazz,portnifo,accord,passat as stored in v_name in table newcar_variants. I want that variants v_name should be displayed only for v_prod_id in table A matches with id in table B
Like, i have created these 2 functions where first function of drop down are working perfectly
<?php
function model_drop_down(){
$database = JFactory::getDBO();
$sql = "SELECT * from #__newcar_products where state='1' order by prod_name Asc";
$database->setQuery($sql);
$rows = $database->loadObjectList();
$list="";
foreach($rows as $row){
$list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->prod_name."</option>";
}
return $list;
}
function variant_drop_down(){
$database = JFactory::getDBO();
$sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
and a.state='1' where 1 order by a.v_prod_id asc";
$database->setQuery($sql);
$rows = $database->loadObjectList();
$list="";
foreach($rows as $row){
$list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->v_name."</option>";
}
return $list;
} ?>
<div class="common-box">
<div class="common-box-left">Car Model*</div>
<div class="common-box-right">
<div id="txtHint">
<select name="model" class="list-box-big" id="model" lang="MUST" title="Model" style="width:245px; height:25px;">
<option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
<?php echo model_drop_down();?>
</select>
</div>
</div>
</div>
<!--box end-->
<!--box start-->
<div class="common-box">
<div class="common-box-left">Sub Model*</div>
<div class="common-box-right">
<div id="txtHintVariant">
<select name="variant" class="list-box" id="brand" lang="MUST" title="Brand">
<option value="" selected="selected" style='padding-left:10px;'>Select Variant</option>
<?php echo variant_drop_down();?>
</select>
</div>
Heres schema of both tables
As of now the fields displaying all models and name of all variants. Whats happening now in second field of variant its displaying all value stored in v_name rather than only those under v_name where v_prod_id in newcar_variants matches with id in newcar_products
I think a way needed which
Step 1 When a user select Model from drop down in the first field, the varle of field id needs to be stored in newcar_products
Step 2 Then in second field of select variant, when the user select drop down of model in the first field. the value of 'id' as stored in newcar_products should match with the v_prod_id in the second table newcar_variants and thus the list of variants to be displayed in matching 'v_name'
How to create the function to achieve desired.
Can anyone help, been novice this would be a great learning. thanks
I took your code and added the missing features, after stubbing the DB connection.
You can try it live using the link below :
https://code.sololearn.com/wm6EGyHmt5cj
Just click the green "RUN" button and you will be able to select a model in the dropdown and to see the variants being filtered accordingly.
And here is the full code as well (in case this link expires):
<?
function getModel($id, $name) {
$row = new stdClass();
$row->id = $id;
$row->prod_name = $name;
return $row;
}
function getVariant($id, $name, $modelId) {
$row = new stdClass();
$row->id = $id;
$row->v_name = $name;
$row->v_prod_id = $modelId;
return $row;
}
function model_drop_down(){
//---YOUR CODE COMMENTED BELOW---
// $database = JFactory::getDBO();
// $sql = "SELECT * from #__newcar_products where state='1' order by prod_name Asc";
// $database->setQuery($sql);
// $rows = $database->loadObjectList();
//---END OF YOUR COMMENTED CODE---
//---MY DB STUB BELOW
$rows = [];
array_push($rows, getModel(0, 'Ferrari'));
array_push($rows, getModel(1, 'Honda'));
array_push($rows, getModel(2, 'Volkswagen'));
//---END OF MY DB STUB
$list="";
foreach($rows as $row){
$list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->prod_name."</option>";
}
return $list;
}
function variant_drop_down(){
//---YOUR CODE COMMENTED BELOW---
// $database = JFactory::getDBO();
// $sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
// and a.state='1' where 1 order by a.v_prod_id asc";
// $database->setQuery($sql);
// $rows = $database->loadObjectList();
//---END OF YOUR COMMENTED CODE---
//---MY DB STUB BELOW
$rows = [];
array_push($rows, getVariant(0, '250 GTO', 0));
array_push($rows, getVariant(1, 'F430', 0));
array_push($rows, getVariant(2, 'F40', 0));
array_push($rows, getVariant(3, 'Civic', 1));
array_push($rows, getVariant(4, 'CR-V', 1));
array_push($rows, getVariant(5, 'Golf', 2));
array_push($rows, getVariant(6, 'Polo', 2));
array_push($rows, getVariant(7, 'Passat', 2));
//---END OF MY DB STUB
$list="";
foreach($rows as $row){
$list.="<option value='".$row->id."' data-v_prod_id='".$row->v_prod_id."' style='padding-left:10px;'>".$row->v_name."</option>";
}
return $list;
}
?>
<div class="common-box">
<div class="common-box-left">Car Model*</div>
<div class="common-box-right">
<div id="txtHint">
<select name="model" class="list-box-big" id="model" lang="MUST" title="Model" style="width:245px; height:25px;">
<option value="" selected="selected" style="padding-left:10px;"> Select Model</option>
<?php echo model_drop_down();?>
</select>
</div>
</div>
</div>
<!--box end-->
<!--box start-->
<div class="common-box">
<div class="common-box-left">Sub Model*</div>
<div class="common-box-right">
<div id="txtHintVariant">
<select name="variant" class="list-box" id="brand" lang="MUST" title="Brand">
<option value="" selected="selected" style='padding-left:10px;'>Select Variant</option>
<?php echo variant_drop_down();?>
</select>
</div>
</div>
</div>
<script>
//wait for html DOM loaded
document.addEventListener("DOMContentLoaded", function(event) {
//listen to "model dropdown changed by user" event
document.getElementById("model").onchange = function filterVariants(){
//get the currently selected model
const selectedModelId = document.getElementById('model').value;
if(selectedModelId=="") {
//if no model is selected, show all the variants (set display=block for all options)
for(option of document.querySelectorAll('#brand>option')) {
option.style.display='block';
}
} else {
//if a model is selected, show the only variants having 'data-v_prod_id' attribute equal to the id of the selected model, plus the defaul "Select Variant" option
for(option of document.querySelectorAll('#brand>option')) {
if(option.getAttribute('data-v_prod_id')==selectedModelId) {
//variant from the selected model => show the option
option.style.display='block';
} else if(option.value=="") {
//default option (the one with "Select Variant") => show it
option.style.display='block';
option.selected=true;
} else {
//else, it's a variant from another model => hide it
option.style.display='none';
}
}
}
//reset the variant dropdown to default "Select Variant" value
document.querySelector('#brand>option[value=""]').selected=true
};
});
</script>
Here is the description of my changes:
1. Mockup Data
Of course, I don't have access to your DB, so I replaced the SQL connection and query with a few lines of code to create mockup data:
function getModel generates a model object that looks like a SQL model result row
function getVariant generates a variant object that looks like a SQL variant result row
Then in your model_drop_down function, I manually created data to populate $rows in order to have $rows look the same than the result of your SQL query:
array_push($rows, getModel(0, 'Ferrari'));
array_push($rows, getModel(1, 'Honda'));
array_push($rows, getModel(2, 'Volkswagen'));
For instance, the last line means I'm creating a mockup model with id=2 and name='Volkswagen'
Then I did the same with variants in your variant_drop_down function:
array_push($rows, getVariant(0, '250 GTO', 0));
array_push($rows, getVariant(1, 'F430', 0));
array_push($rows, getVariant(2, 'F40', 0));
array_push($rows, getVariant(3, 'Civic', 1));
array_push($rows, getVariant(4, 'CR-V', 1));
array_push($rows, getVariant(5, 'Golf', 2));
array_push($rows, getVariant(6, 'Polo', 2));
array_push($rows, getVariant(7, 'Passat', 2));
For instance, the last line means I'm creating a mockup variant with id=7, name='Passat' and v_prod_id=2 (which is Volkswagen).
Ok, now I have stubbed your database, we can start coding!
2. Change the SQL variants query to get them all and select the 'v_prod_id' field
The variant_drop_down function will be called only once (php is a server side language, it runs once to render the html code of the page, and is never run again), so we need to get all the data at once, and retrieve the v_prod_id field in order to memorize which variant belongs to which model (we'll use this information in the next steps)
So we'll change 2 things in the query :
Remove the JOIN ON a.v_prod_id = b.id
Add a.v_prod_id in the SELECT clause
So from this:
SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id and a.state='1' where 1 order by a.v_prod_id asc
You will end up with something like this:
SELECT a.id, a.v_name, a.v_prod_id FROM #__newcar_variants a where a.state='1' order by a.v_prod_id asc
3. Add the v_prod_id on each item of the variant dropdown
This is done by adding data-v_prod_id='".$row->v_prod_id."' in your code.
Here is what the html code of the variant dropdown looks like, now:
<select name="variant" class="list-box" id="brand" lang="MUST" title="Brand">
<option value="" selected="selected">Select Variant</option>
<option value="0" data-v_prod_id="0">250 GTO</option>
<option value="1" data-v_prod_id="0">F430</option>
<option value="2" data-v_prod_id="0">F40</option>
<option value="3" data-v_prod_id="1">Civic</option>
<option value="4" data-v_prod_id="1">CR-V</option>
<option value="5" data-v_prod_id="2">Golf</option>
<option value="6" data-v_prod_id="2">Polo</option>
<option value="7" data-v_prod_id="2">Passat</option>
</select>
As you can see, we have data-v_prod_id on each variant.
Now, for each option in the variant dropdown, we know which model it's related to.
So, using javascript, each time the user will change the model, we can filter the displayed variants having v_prod_id equal to the selected model.
4. Dynamic variant filtering using javascript
Each time the user will change the model, we will filter the variant dropdown accordingly.
This is the script to do it, I have put comments on each line to explain the details:
<script>
//wait for html DOM loaded
document.addEventListener("DOMContentLoaded", function(event) {
//listen to "model dropdown changed by user" event
document.getElementById("model").onchange = function filterVariants(){
//get the currently selected model
const selectedModelId = document.getElementById('model').value;
if(selectedModelId=="") {
//if no model is selected, show all the variants (set display=block for all options)
for(option of document.querySelectorAll('#brand>option')) {
option.style.display='block';
}
} else {
//if a model is selected, show the only variants having 'data-v_prod_id' attribute equal to the id of the selected model, plus the defaul "Select Variant" option
for(option of document.querySelectorAll('#brand>option')) {
if(option.getAttribute('data-v_prod_id')==selectedModelId) {
//variant from the selected model => show the option
option.style.display='block';
} else if(option.value=="") {
//default option (the one with "Select Variant") => show it
option.style.display='block';
option.selected=true;
} else {
//else, it's a variant from another model => hide it
option.style.display='none';
}
}
}
//reset the variant dropdown to default "Select Variant" value
document.querySelector('#brand>option[value=""]').selected=true
};
});
</script>
I hope my answer satisfies you.
Again, you can try it live by clicking this link : https://code.sololearn.com/wm6EGyHmt5cj then clicking the green "RUN" button.
<optgroup> May this HTML tag can help you?
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Optgroup
Then you have only one DB query:
function variant_drop_down(){
$database = JFactory::getDBO();
$sql = "SELECT b.prod_name, a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products b ON a.v_prod_id = b.id
and a.state='1' where 1 order by a.v_prod_id asc";
$database->setQuery($sql);
$rows = $database->loadObjectList();
$list="";
$label=null;
foreach($rows as $row){
if ($label!=$row->prod_name) {
if (null!==$label) {
$list.="</optgroup>";
}
$label=$row->prod_name;
$list.='<optgroup label="'.$label.'">';
}
$list.="<option value='".$row->id."' style='padding-left:10px;'>".$row->v_name."</option>";
}
if (null!==$label) {
$list.="</optgroup>";
}
return $list;
} ?>
As whatever you are trying to achieve that would not be done through PHP alone. You have to use JQuery/JavaScript to achieve the result.
If your Models and Variants are static then use the code of Vincent but to do dynamic you have to use below code.
I am just giving the idea you have to workout the exact solution of ajax based solution.
This would be first drop out option as:
<select name="model" id="model">
<?php echo model_drop_down();?>
</select>
<select name="variant" id="variant">
</select>
Your Jquery code would be like this:
$(document).ready(function() {
$('#model').change(function() {
$.ajax({
type : 'POST',
url : 'variant.php',
dataType : 'json',
data: {
model : $('#model').val()
},
success: function(data){
$('#variant >option').remove();
var s= document.getElementById('model');
s.options[s.options.length]= new Option('Kindly Select Variant', '');
$.each(data.variant, function() {
s.options[s.options.length]= new Option(this, this);
})
}
});
});
})
Your variant.php file
//I don't know the exact variant value but the post value is the mode id number here
// $_POST["model"] = $row->id
$database = JFactory::getDBO();
//Create the query to exact the only variants of model number here
$sql = "SELECT a.id, a.v_name FROM #__newcar_variants a JOIN #__newcar_products
b ON a.v_prod_id = b.id and a.state=$_POST["model"] where 1 order by a.v_prod_id asc";
$database->setQuery($sql);
$rows = $database->loadObjectList();
foreach($rows as $row){
$t[]= $row->v_name;
}
$return['variant']=$t;
echo json_encode($return);
It is not the exact solution but a basic idea more you have to do changes according to your needs. This example may contain some minor error as it is not run

Query new data based on combobox, and display it in new textbox

I have a combobox that contains a project number id. Based on the selection of this combobox I want to display the amount of rows in another table containing the same project number id. This value will be appended to the blue box "Number of POs".
My file "new-customer-po.php". I'll display it in parts for simplicity.
<?php
//Query for projectnumber
$query_1 = "SELECT PROJECTNOID, ProjectNumber, ProjectTitle, (SELECT (SELECT
CustomerName FROM tblCustomers WHERE Customer = CUSTOMERID) AS Customer
FROM tblCustomerContacts WHERE CustomerProjectLeadID =
CUSTOMERCONTACTID) AS CustomerProjectLeadID FROM tblProjects ORDER BY
ProjectNumber DESC";
$result_1 = mysqli_query($conn, $query_1);
$options_1 = "";
while($row_1 = mysqli_fetch_array($result_1))
{
$options_1.='<option value="'.$row_1[0].'">'.$row_1[1]." - ".$row_1[2]." - ".$row_1[3].'</option>';
}
?>
further down this page I have the following html
<label>Project Number <b style="color:red;">*</b></label>
<select id="proj" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title - Customer --</option>
<?php echo $options_1; ?>
</select><br>
<div id="currentnumpo">
<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" readonly/><br>
</div>
and after the closing html tag
<script type="text/javascript" >
jQuery(document).ready(function($) {
$("#proj").on('change', function() {
var num = $(this).val();
if(num){
$.ajax ({
type: 'POST',
url: 'getnumberpo.php',
data: { num },
success : function(htmlresponse) {
$('#currentnumpo').html(htmlresponse);
console.log(htmlresponse);
}
});
}
});
});
</script>
My "getnumberpo.php"
<?php
echo $_POST['projectnum'];
if(isset($_POST['projectnum'])){
$sql = "SELECT COUNT(*) FROM tblCustomerPOs WHERE ProjectNum = '".$_POST['projectnum']."'";
$result = $conn->query($sql);
if ($sql) {
while($row = $conn->query($sql)) {
echo '<label>Number of POs</label><input name="numpos" class="inputvalues" id="reqtxtfield" placeholder="';
echo $row[0];
echo '" readonly/><br>';
}
}
$sql = NULL;
}
?>
I'm very new to javascript/ajax so i'm sorry if none of what i'm doing makes sense.
So far when I change the dropdown the whole textbox for "number of po's" dissappears. I've ran the query on "getnumberpo.php" on mysql workbench and it works just fine.
Ex: When I select a project from the dropdown. It will query another table called tblCustomerPOs and check how many rows contain the project number that was selected.
Thanks for the help
If anyone comes across this in the future and wanted the answer...
getnumberpo.php (Server-Side Script)
<?php
require "../inc/dbinfo.inc";
$projectnum =$_POST['projectnum'];
$sql = mysqli_query($conn, "SELECT COUNT(*) AS mycount FROM tblCustomerPOs WHERE ProjectNum = '$projectnum'"); //RESPONSE IS QUERY WITH REAL $PROJECTNUM
$res = mysqli_fetch_object($sql)
$count = $res->mycount;
echo json_encode($count);
exit();
?>
new-customer-po.php (Javascript)
//AUTO UPDATE NUMBER OF POS
$(document).ready(function(){
$('#projectnum').change(function(){
var projectnum = $(this).val();
var data_String;
data_String = 'projectnum='+projectnum;
$.post('getnumberpo.php',data_String,function(data){
var data = jQuery.parseJSON(data);
$('#currentnumpo').val(data)
});
});
});
new-customer-po.php (html)
<label>Project Number <b style="color:red;">*</b></label>
<select id="projectnum" name="projectnum" class="inputvalues" required>
<option disabled selected value>-- Project # - Title</option>
<?php echo $options_1; ?>
</select><br>
<label>Number of Customer POs</label><input type="text" name="currentnumpo" id="currentnumpo" class="inputvalues" readonly/><br>

Pre Populating a PHP Dynamic Select Option with Stored Session Variable

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

<select><option> and action associated with them

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.

Creating and populating a select dynamically

I have 2 tables, Provinces and Districts. I would like to populate a select field with options as District names based on which Province is chosen in another select. The Districts table has a ProvinceID field to reference which Province it belongs to. I know this is doable, I just can't figure it out. I also want to create and update the new Districts select without refreshing the page.
UPDATE: I'm writing it in PHP and MySQL, using jQuery as sparingly as possible.
In order to do it without AJAX, prepopulate a Javascript dataset... warning, if you have a lot of data this could be slow, but if it's a manageable list length, you could save some overhead from multiple AJAX requests loading the same data over and over.
var provinces = {};
provinces['province_a_id'] = [
{ name:'District A', id:'district_a_id' },
{ name:'District B', id:'district_b_id' }
];
provinces['province_b_id'] = [
{ name:'District C', id:'district_c_id' },
{ name:'District D', id:'district_d_id' }
];
function getDistricts( referenced_select ) {
var selected_province = $(referenced_select).val();
var district_select = $('#districts');
district_select.empty();
if ( provinces[selected_province] ) {
$.each( provinces[selected_province], function(i,v) {
district_select.append( $('<option value="' + v['id'] + '">').text( v['name'] ) );
} );
}
}
$(document).ready( function() {
$('#provinces').bind( 'change', function() {
getDistricts(this);
} );
} );
-- HTML
<select id="provinces" name="provinces">
<option value="province_a_id">Province A</option>
<option value="province_b_id">Province B</option>
</select>
<select id="districts" name="districts">
</select>
Make a php script and call it dp.php ( dp, short for data_provider, use any name you like). In dp.php
// get province id passed in via `post` or `get`
$pid = $_REQUEST['pid'];
// get the districts in that province
$query = "SELECT `district_id`, `district` FROM `districts` WHERE province_id` ='$pid'";
// link to your database
$link = mysqli_connect(HOST, USER, PASS, DBNAME);
// execute your query
$result = mysqli_query($link, $query);
// parse the options
while($row = mysqli_fetch_assoc($result)) {
$options .= '<option value="' . row['district_id'] . '">' . $row['district'] . "</option>\n";
}
// send options
echo $options
With the following markup in your page:
<select id="province" name="province">
<option value="ny">New York</option>
...
</select>
<select id="district" name="district">
</select>
Include the following jQuery:
// whenever a different province is selected
$('#province').change(function() {
// remove all options in district select
$('#district').html('');
// find the new province selected
var my_province = $('#province').val();
// get new options from server and put them in your district select
$('#district').get('path/to/dp.php?pid=' + my_province);
)};
You didn't state what server side technology you are using (if any). Here's an example in ASP.net - it should point you in the right direction:
http://www.mikesdotnetting.com/Article/97/Cascading-DropDownLists-with-jQuery-and-ASP.NET
I actually figured this out on my own using jQuery and post. On the primary select, I added onchange="getDistricts()" and used this for that function:
function getDistricts()
{
var province_id = $("#provinces").val();
$.post("handler.php",
{
"mode" : "get_districts",
"pid" : province_id
},
function(data)
{
$("#districts").html(data);
}, "text");
}
And then in handler.php, I have a case that catches the mode, and runs the following code:
<query on districts table>
while($row = $sql->fetchrow($result);
{
$id = $row['id'];
$name = $row['name'];
$html .= "<option value='$id' id='$id'>$name</option>";
}
echo $html;
I'm not a fan of this solution, and would really like something better, but it does what I need it to do for the moment. I hope this can help someone else out.

Categories