Populate another select dropdown from database based on dropdown selection - php

I am building a website to learn coding and am trying to build a tool where a user clicks on a select/dropdown that contains some category names pulled from database cat and then another select will appear with subcategory names pulled from database subcat. This is almost exactly like Yelp's (go down to the categories) like Yelp's (go down to the categories).
I also made a diagram:
I already have a category dropdown that is pulling from cat database:
<p><b>Category:</b><br />
<?php
$query="SELECT id,cat FROM cat";
$result = mysql_query ($query);
echo"<select name='cselect3' class='e1'><option value='0'>Please Select A Category</option>";
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']." </option>";
}
echo"</select>";
?>
And I have a subcat that is pulling from subcat database:
<p><b>Subcat1:</b><br />
<?php
$query="SELECT id,subcat FROM subcat";
$result = mysql_query ($query);
echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";
}
echo"</select>";
?>
How do I make a subcategory dropdown based on what the user clicks on category and make it automatically appear?
Thanks so much for any and all help!

I would just make put the variables in javascript with php and then use javascript functions.. no jquery or AJAX needed.
However you need to have a foreign key for subcategories no matter what.. ie - For every record in subcat table you need to give it a catid so for referencing...
<?php
$db = new mysqli('localhost','user','password','dbname');//set your database handler
$query = "SELECT id,cat FROM cat";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("id" => $row['id'], "val" => $row['cat']);
}
$query = "SELECT id, catid, subcat FROM subcat";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['catid']][] = array("id" => $row['id'], "val" => $row['subcat']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>

Since the data in your Sub-Category drop down is dependent on what is selected in the category, you probably want to use ajax. You can set an event listener on your category drop down and when it changes you can request the data for the subcategory drop down and populate it, there are many different ways to go about it, below is one option (using jquery) to get you started.
// warning sub optimal jquery code
$(function(){
// listen to events on the category dropdown
$('#cat').change(function(){
// don't do anything if use selects "Select Cat"
if($(this).val() !== "Select Cat") {
// subcat.php would return the list of option elements
// based on the category provided, if you have spaces in
// your values you will need to escape the values
$.get('subcat.php?cat='+ $(this).val(), function(result){
$('#subcat').html(result);
});
}
});
});

If you are using AJAX, you will want that second bit of code to be a separate php file which you will call via AJAX. in the callback from the AJAX call, just do (pseudo-code): someContainingDivOrSomething.innerHtml = responseBody;.
Note that it's generally a bad idea to do querying within your PHP display files directly (separation of concerns). There are several other things that could be improved. However, this will get you started.

make this html structure on landing page
<p><b>Category:</b><br />
<?php
$query="SELECT id,cat FROM cat";
$result = mysql_query ($query);
echo"<select name='cselect3' onChange='loadSubCats(this.value)' class='e1'><option value='0'>Please Select A Category</option>";
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']." </option>";
}
echo"</select>";
?>
<div id='sub_categories'></div>
make a js function assigned to the category dropdown
function loadSubCats(value)
{
$.post('load_sub_cats.php',{catid : value},function{data}
{
$('#sub_categories').html(data);
});
}
now in your load_sub_cats.php
<p><b>Subcat1:</b><br />
<?php
$catid = $_POST['cat_id']
$query="SELECT id,subcat FROM subcat where catid = $catid";
$result = mysql_query ($query);
echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";
}
echo"</select>";
?>
You will need to include jquery to this code work.

Related

Using droplist from database set value of another droplist based on the selection of the first one

I have this table
Device Name Price
iPhone 6 300
S8 600
What I am trying to do is have to drop list one that has all the devices Name and the second has an option "Price" but I want to set its value based on the selection of the device name. However, in the drop list it should just display "Price"
I have this php code for the drop lists
$query = "SELECT * FROM `devicehotsheet`";
$options = "";
$result1 = mysql_query($query, $dbhandle);
while ($row1= mysql_fetch_array($result1)){
$options=$options."<option>$row1[0]</option>";
}
For HTML
<select class="selectDevice" id="selectDevice" onChange="calculateTotal()">
<?php echo $options; ?>
</select>
<select class="myport" id="myport" onChange="calculateTotal()">
<option class="price" value=" ">Price</option>
</select>
I have been trying to do this but so far no luck. I would appreciate your help. Thanks
$query = "SELECT * FROM `devicehotsheet`";
$options = "";
$result1 = mysql_query($query, $dbhandle);
while ($row1= mysql_fetch_array($result1)){
$options=$options."<option value='$row1[0]#$row1[1]'>$row1[0]</option>";
}
and the javascript code
function calculateTotal(){
var selDev = document.getElementById('selectDevice').value;
var price = selDev.split('#')[1];
document.getElementById('myport').innerHTML='<option>'+price+'</option>'
}

How to fill one combo box basing other combo box selected value

I have created two tables "category" and "subcategory". So what i need to do is that i have organized two combobox and one will retrieve values from category table and populate the data. However, i need to fill the other combobox when one selected from the category combobox and populate all the values from subcategory table.
I really thank you all for helping me out.
Looking for great answer.
Thank you in advance.
You will probably want to use AJAX and php to do this....
First, if you don't have a jquery library, you can get it at http://jquery.com/download/
This will enable you to use AJAX jquery.
In your html header:
<script>
$(document).ready(function() {
$("#category").change(function() {
var selectVal = $('#category :selected').text();
$.ajax({
url: 'getsubcat.php',
data: "groupid="+selectVal,
type:'post',
//dataType: 'json',
success: function(data)
{
$('#subcat').html('<option value="">'+data+'</option>');
}
});
});
});
</script>
In the html body --
<?php
include('conn.php');
$sql = "SELECT * FROM categories";
$result3 = pg_query($con, $sql);
?>
<!-- first select list -->
Select a category: </td><td>
<select id="category" name="category">
<option value = ""></option>
<?php
while($row = pg_fetch_array($result3)) {
echo '<option >'.$row[1].'</option>';
}
?>
</select>
<?php
$sql = "SELECT * FROM subcategories where cat = '$cat'";
$result3 = pg_query($con, $sql);
?>
Select a sub category:
<select id="subcat" name="subcat">
<option value = ""></option>
<?php
while($row = pg_fetch_array($result3)) {
echo '<option>'.$row[1].'</option>';
}
?>
</select>
Finally, in your php file -- getsubcat.php
<?php
$category = $_POST['groupid'];
include('conn.php');
$sql="select * from subcat where cat_name = '$category'";
$result = pg_query($con, $sql);
while($row = pg_fetch_array($result)) {
echo '<option>'.$row[1].'</option>';
}
pg_query($sql) or die("Error: ".pg_last_error());
?>
All of this will allow you to have your select lists dynamic an dependent on the first one.
Here I am using postgresql for the database, but you should be able to change the connection string (conn.php) and the table names, columns if you are using a different database like mysql.

PHP Dynamic drop down list for deleting rows

I am creating a deletion page for the removal of rows in the database. I have everything working up until the actual removal of the rows upon submit. The records display in the drop down without problem, any ideas of a solution are appreciated. (I am using deprecated SQL, I know.)
1ST PART OF PHP (FORM)
$query = 'SELECT event_name FROM event';
$result = mysql_query($query);
echo "<select name='events' value='-'>\n";
echo "<option value='Select event'>Select an event to be deleted\n";
while($row = mysql_fetch_row($result))
{
$eventSelect = $row[0];
echo "<option value='$eventSelect'>$eventSelect</option>\n";
}
echo "</select>"
2ND PART OF PHP (DELETION)
if (isset($_POST['eventSelect']))
{
$eventselection = $_POST['eventSelect'];
$query = "DELETE FROM event WHERE event_name = '$eventselection'";
$result = mysql_query($query);
}

UPDATE reflected in DB but not SELECT query

First time for me here.
I am using PHP, MySQL, JavaScript and running JQUERY and AJAX functions.
I have an anchor link that runs a function.
The function emptys a DIV tag and then fills/displays (SELECT query) a table of rows in the DIV with a is null where clause. Each row has a select box where the NULL data column would go. The data in the select box comes from a different table.
When the select box changes it immediately runs the ajax to UPDATE the table row with the new data in the select box.
When you click the link to run the function again (empty, select query and display based on null column) the row that was just updated to the DB shows up again based on the is null clause. Checking the DB table at this point shows that it is in fact not null and was UPDATEd properly the first go around.
The page is never refreshed during this process and never has to be. If I do refresh it shows the proper data without the BUG.
All your thoughts are greatly appreciated.
matt
function closeItemsBtn() { // called by a click function of a standard link/button
$('#CloseItems').empty(); // remove all html from the DIV
var newAppend = '';
<?
//[... connect to db ...]
// select info from 2 different tables so it can be used in different locations if necessary
// where the row has not been reviewed and therefore is null
$query = "select * from nearmiss where reviewedId is null order by submitDate desc";
$result = $db->query($query) or die($db->error);
$query2 = "select * from hazardid where reviewedId is null order by submitDate desc";
$result2 = $db->query($query2) or die($db->error);
$num_rows = $result->num_rows;
$num_rows2 = $result2->num_rows;
// create html for the DIV tag. Creates a table in a DIV that collapses by clicking aCloseList.
// each row is in tbody so it can be striped by a all purpose striping function
// this part is the table header and opening div tags and link
$newAppend = "<p id=\"closeList\">Show/Hide {$num_rows} Near Misses requiring attention.</p><div id=\"closenearmiss\" style=\"display:none;\"><table class=\"closenearmisstable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
// update various foreign key information from other tables
for ($i=0;$i<$num_rows;$i++) {
$row = $result->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
// here is the table itself with the select tag in the null column name=reviewed
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"nearmissreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['nearmissId']}\"><input type=\"hidden\" name=\"type\" value=\"nearmiss\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Near Miss</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
// this is the beginning of the second table same structure as first with collapsing but
// different data
$newAppend .= "<p id=\"closeList\">Show/Hide {$num_rows2} Hazard IDs requiring attention.</p><div id=\"closehazardid\" style=\"display:none;\"><table class=\"closehazardidtable\"><tbody><tr><td>Date Submitted</td><td>Submitted By</td><td>Location</td><td>Reviewed By</td></tr><tr><td rowspan=\"2\">Type</td><td colspan=\"3\">Description / Observation</td></tr><tr><td colspan=\"3\">Action / Reinforcement</td></tr></tbody>";
for ($i=0;$i<$num_rows2;$i++) {
$row = $result2->fetch_assoc();
$query3 = "select location from locations where locationId='{$row['locationId']}'";
$result3 = $db->query($query3);
$location = $result3->fetch_assoc();
$query3 = "select name from employees where employeeId='{$row['employeeId']}'";
$result3 = $db->query($query3);
$name = $result3->fetch_assoc();
$newAppend .= "<tbody><tr><td>{$row['submitDate']}</td><td>{$name['name']}</td><td>{$location['location']}</td><td><form name=\"hazardidreview\" action=\"\" method=\"\"><input type=\"hidden\" name=\"docId\" value=\"{$row['hazardidId']}\"><input type=\"hidden\" name=\"type\" value=\"hazardid\"><select name=\"reviewed\"><option>Choose name to sign off</option></select></form></td></tr><tr><td rowspan=\"2\">Hazard ID</td><td colspan=\"3\">{$row['description']}</td></tr><tr><td colspan=\"3\">{$row['action']}</td></tr></tbody>";
}
$newAppend .= "</table></div>";
echo "newAppend='{$newAppend}';";
$result->free();
$result2->free();
$result3->free();
$db->close();
?>
// put HTML of $newAppend php in the DIV
$('#CloseItems').append(newAppend);
// fill the select box with a variable set somewhere else in the code not displayed here
$('#CloseItems select[name=reviewed]').append(newAppendE);
stripePointsTable('.closenearmisstable tbody');
stripePointsTable('.closehazardidtable tbody');
// close list click options
$('#closeList > a').each(function() {
$(this).click(function() {
if ($(this).parent().next().css('display')=='none') {
$(this).parent().next().slideDown('slow');
} else {
$(this).parent().next().slideUp('fast');
}
});
});
// select tag change function that calls ajax and displays a message in a DIV called header
$('#closenearmiss select').change(function() {
function processDataClose(data, success) {
if (success) {
$('#header').prepend(data+"<br />");
closeItemsBtn();
} else {
$('#header').prepend(data+"<br />");
}
}
var formData = $(this).parent().serialize();
$.post('processreviewsign.php',formData,processDataClose);
});
jQuery caches your ajax calls. This is likely why you see the correct result when you refresh the page, but not in subsequent calls via ajax.
Try setting cache: false in your ajax call

Keeping lastly selected value from a dropdownlist after button click

Just like the title says i'm having difficulties in achieving it.
Here's my dropdownlist:
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[data] name=\"blabla\">$nt[data]</option>";
}
echo "</select>";
?>
Here's the buttonclick:
<?php
if(isset($_POST['Submit']))
{
$query = "SELECT SUM(suma), paskirtis FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' AND data ='".$_POST['data']."' group by paskirtis";
$result = mysql_query ($query);
echo "<tr><td>Paskirtis:</td><td>Biudzetas:</td><td>Isleista:</td><td>Likutis:</td></tr>";
while($nt=mysql_fetch_array($result)){
if($nt['SUM(suma)'] != null){
$suma = $nt['SUM(suma)'];
}
echo "<tr><td>$nt[paskirtis]</td>
<td><input type=\"text\" name=\"isleista[]\" value=\"Skiriamų pinigų kiekis...\" method=\"post\"></td><td>".$suma." Lt</td><td>--</td></tr> <br>";
}
}
?>
After I press it, it retrieves the data I want from the date I've chosen from the drop down list and also reset whole drop down list showing the first value of the dates from sql database, not the one I selected. If anyone knows how to keep the selected value in the list any help is greatly appriciated!
Try this, you need to place select="selected" in the while loop. See below code how I placed the $selected
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
$selected = ($_POST['blabla'] == $nt[data])?'selected="selected"':NULL;
echo "<option value=$nt[data] name=\"blabla\" $selected >$nt[data]</option>";
}
echo "</select>";
?>

Categories