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.