Reputation: 91
I'm learning Php & Mysql.
I've a database(practice) with 2 table. One is Category and other is sub-category.
In my html form there are a list of select box data which is come from Category table. So i need, if i select this list box, them another select box data will be appear from sub-category table which is related to Category table. For example:
Category table
Id Cat_name
1 O level
2 A level.
Sub-Category table:
id Cat_id Sub_name
1 1 O-level Math
2 1 O-level English
3 2 A-level Math
4 2 A-level English
Thanks in Advance.
Upvotes: 1
Views: 884
Reputation: 1161
If you want this to be done seamlessly and efficiently without page reloads you will need to look into the Jquery Ajax function. The way Ajax works is when someone makes a selection in the first box, it will send that data to a php script that can take the answer from the first box, run a mysql query, then return the new subcategories to the original page without having to reload the page.
Example: In your test.php
//On selection change state, call the ajax
$("#elementid").change(function() {
var selection = $(this).children("option:selected");
$.ajax({
url: 'caller.php',
dataType: 'json',
data: 'selected='+selection,
success: function(data) {
//Fill the second selection with the returned mysql data
}
});
}
<select id="elementid">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
In your caller.php
$selection = $_POST["selected"];
//Create an array to hold all the subcategories, say the array is called $sub
echo json_encode(array(success => $sub));
exit;
Please read up on Jquery.ajax
Upvotes: 1
Reputation: 3546
You will need Ajax to get this done, upon selecting a value in your first drop down, you send a request via ajaxnto another php file that will give you the resulting subcategories, based on the first selection. Ajax will then insert this new data in your second dropdown. You can also look into the post function from the jquery library, which will make this whole process even easier.
Upvotes: 0