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.
Related
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>'
}
As I've tried to describe in the title I have an issue in selecting rows from a MYSQL database depending on the id of another drop down list on the same page. I have only been using mysql and php for 2 months or so now and need help.
I have a table of categories with the below headers.
|id | name | parent_id|
There are parent categories, with a parent_id of 0. And Sub categories with the id of the parent as their parent_id, to a maximum depth of 1 child category. For example:
Software Development is a parent category with id = 18 and parent_id = 0. PHP Developer is a subcategory which has id = 30 and parent_id = 18.
I have a drop down list where I can select the category I work in as follows:
$p_query = "SELECT * FROM categories WHERE parent_id = 0 ORDER by id ASC";
$p_result = mysqli_query($con, $p_query) or die(mysqli_error($con));
$categories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$categories .='<option class="option" value="p::'.$p_row['id'].'">' .$p_row['category_name'].'</option>';
}
<select name="categories[]" class="categories form-control" id="categories" style="width:100%" multiple>
<?php echo $categories;?>
</select>
This is working, no problem. However, when I try to get a second drop down list to show the possible categories whom have their parent_id as the id of any selected parent category I retrieve a drop down list with 'No Search Results found'. The code below is what I am using :
$subcategories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$c_query = "SELECT * FROM categories WHERE parent_id = ".$categories['id']." ORDER by id ASC";
$c_result = mysqli_query($con, $c_query) or die(mysqli_error($con));
while($c_row = mysqli_fetch_assoc($c_result))
{
$subcategories .='<option class="option" value="c::'.$c_row['id'].'">' .$c_row['category_name'].'</option>';
}
}
<select name="subcategories[]" class="categories form-control" id="subcategories" style="width:100%" multiple>
<?php echo $subcategories ?>
</select>
Is there something that I am missing? As a relative beginner to both PHP and MYSQL, I would be very appreciative of any help or advice.
There is nothing wrong with your second query to retrieve sub-categories based on their parent_id so you're good there. You can test easily like so:
SELECT * FROM categories WHERE parent_id = 1 ORDER by id ASC
How are you providing the value to $categories['id'] as there is nothing in your code creating this array with an 'id' index? Further you already are using a variable called $categories as a string so you shouldn't re-use that variable name without good reason.
Since it appears you want to populate the second multiple select box with subcategories based on the selection of the first you will need to use some javascript+AJAX to submit the second query and write the results in the second selector element.
Using some jquery should help a bit. Try these examples and you'll get the idea.
myselect.php which contains the interface for selecting the category:
<?php
$con = mysqli_connect("host", "username", "password", "database");
$p_query = "SELECT * FROM categories WHERE parent_id = 0 ORDER by id ASC";
$p_result = mysqli_query($con, $p_query) or die(mysqli_error($con));
$categories ='';
while($p_row = mysqli_fetch_assoc($p_result))
{
$categories .='<option class="option" value="p::'.$p_row['id'].'">' .$p_row['category_name'].'</option>';
}
?>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous">
</script>
</head>
<body>
Shift or Ctrl + Click to pick more than one<br />
<form id="categoryform" method="POST">
<select name="categories[]" class="categories form-control" id="categories" style="width:100%" multiple>
<?php echo $categories;?>
</select>
</form>
Here's what it contains<br />
<form method="POST">
<select name="subcategories[]" class="categories form-control" id="subcategories" style="width:100%" multiple DISABLED>
</select>
</form>
<script>
$(document).ready(function() {
$('#categories').click(function(){
$('#subcategories').children().remove().end();
var data = $('#categoryform').serialize();
$.post("mysubselect.php", data).done(function(data){
var response = JSON.parse(data);
for (var k in response){
$('#subcategories').append('<option class="option" value="c::' + response[k]['id'] + '">' + response[k]['category_name'] + '</option>');
}
});
});
})
</script>
</body>
</html>
And here's an example of the script returning data from your AJAX request.
mysubselect.php:
<?php
$con = mysqli_connect("host", "username", "password", "database") or die(mysqli_error());
$result = array();
foreach ($_POST["categories"] as $k => $v) {
$category_token = explode('::', $v);
$category_id = mysqli_real_escape_string($con, $category_token[1]);
$query = mysqli_query($con, "SELECT * FROM categories WHERE parent_id = " . $category_id . " ORDER BY id ASC") or die(mysqli_error());
while($r = mysqli_fetch_assoc($query)){
$result[] = $r;
}
}
print json_encode($result);
How do I filter dropdown options to list my table entries?
HTML filter example:
<form action="filter.php" method="post">
<select name="filter">
<option>FILTER:</option>
<option value="alphabetical">ASC</option>
<option value="date">Date</option>
</select>
</form>
Basic MySQL select:
SELECT * FROM table ORDER BY name
Basic HTML that lists values:
echo '<h1>'.$name.'</h1>
<h1>'.$date.'</h1>';
The second filter (date) should do a SELECT that lists all the entries with ASC dates. The second first one (alphabetical) should do a SELECT that lists all the name's entries by ASC only.
Any idea of how the MySQL SELECT would work in that case?
html:
<select name="filter" onchange="filter(this.value)">
<option>FILTER:</option>
<option value="alphabetical">ASC</option>
<option value="date">Date</option>
</select>
<div id="results"></div>// store the results here
Jquery:
function filter(item){
$.ajax({
type: "POST",
url: "filter.php",
data: { value: item},
success:function(data){
$("#results").html(data);
}
});
}
filter.php:
include "connection.php"; //database connection
$fieldname = $_POST['value'];
if($fieldname=="alphabetical"){
// if you choose first option
$query1 = mysqli_query("SELECT * FROM table ORDER BY name ASC");
// echo the results
}else{
// if you choose second option
$query1 = mysqli_query("SELECT * FROM table ORDER BY date ASC");
// echo the results
}
Note: Do not forget to include jquery library.
These should work, assuming name and date are the field names in the table.
SELECT * FROM table ORDER BY name ASC
SELECT * FROM table ORDER BY date ASC
I would do something like this,
HTML:
<form action="filter.php" method="post">
<select name="filter">
<option>FILTER:</option>
<option value="alphabetical">ASC</option>
<option value="date">Date</option>
</select>
</form>
PHP
<?php
switch($_POST['filter']){
case "alphabetical":
$field = "name";
break 1;
case "date":
$field = "date";
break 1;
}
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$stmt = $mysqli->prepare("SELECT * FROM table ORDER BY ? ASC");
$stmt->bind_params("s",$field);
$stmt->execute();
//ETC
?>
I have a select box like
<select id="addressbook_user" name="addressboook_user">
<?php
$asql = "SELECT * from demo_addressbook WHERE user_created_id IN(SELECT id FROM demo_user WHERE user_name = '$get_user_name') AND type = 1 ";
// $result = mysql_query($query);
// mysql_real_escape_string($asql);
$aresult = mysql_query($asql) or die (mysql_error());
while($arow_list=mysql_fetch_assoc($aresult)){
?>
<option value="<?php echo $arow_list['guest_name']; ?>"><?php echo $arow_list['guest_name']; ?></option>
<?php
}
?>
</select>
Here is my jQuery code to get this value .
function save() {
alert($("#addressboook_user").val());
var selectVal = $('#addressboook_user :selected').val();
alert(selectVal);
var user = $("#addressboook_user").val();
}
My question is when select box has a selected value then why my jQuery code alert is always showing undefined ?
please help me out here really got frustrated .
You havn't used ID of select box
Change
alert($("#addressboook_user").val());
To
alert($("#addressbook_user").val());
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.