I’m pretty new to php but i’m learning pretty fast, I have a question I hope you pro’s may be able to help me with. I’ve done some googling and can’t find the answer.
I’m trying to do a dynamic dropdown menu with two levels – I have set up a database and have installed the data, the first level has a primary key and category name, the next level has a primary key, foriegn key and a subcategory name.
I have created a do while loop for the categories which works super! Now I’m trying to insert the sub categories. I’ll trying to summarise what I am trying to acheive.
Do while loop of the categories in between each catergory run another loop display all of the sub categories where the primary key of the category matches the foriegn key of the sub categories. Then continue.
e.g.
Category
Sub category
Sub category
Sub category
Category
Sub category
Category
Sub category
Sub category
and so on….
Any advice on how this would be coded?
I hope this makes sense.
Thank you in advance!
Kindest Regards.
<?php
// Query member data from the database and ready it for display
$category_sql = "SELECT * FROM tm_product_category";
$category_query = mysql_query($category_sql) or die(mysql_error());
$categorylist = mysql_fetch_assoc($category_query);
?>
<?php
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Query member data from the database and ready it for display
$subcategory_sql = "SELECT * FROM tlk_sub_cat";
$subcategory_query = mysql_query($subcategory_sql) or die(mysql_error());
$subcategorylist = mysql_fetch_assoc($subcategory_query);
?>
<?php do { ?>
<ul><li><a href="category.php?pk_cat_id=<?php echo $categorylist['pk_cat_id'];?>"><?php echo $categorylist['category']; ?></a></ul>
<?php
if ($categorylist['pk_cat_id'] == $subcategorylist['fk_cat_id'])
{
do { ?>
<li><a href="subcategory.php?pk_cat_id=<?php echo $subcategorylist['pk_sub_cat_id'];?>"><?php echo $subcategorylist['txt_sub_cat']; ?></a></li>
<?php } while ($subcategorylist = mysql_fetch_assoc($subcategory_query));
; }
?>
<?php } while ($categorylist = mysql_fetch_assoc($category_query));
?>
All i’m getting ATM is;
Category
List of all of the subcategories
Category
Space
Category
Space
Category
Space
until categories run out.
You could execute a single query with a
JOIN, such asINNER JOIN, then iterate through the returned set of records. If the previous foreign key is different than the current foreign key, you are on a new primary record, {do magic} related to primary record and then {do magic} for the current sub record, otherwise, just {do magic} for the current sub record.edit:
You reference each tables’ fields by prepending the table name and a period. AFAIK with mysql, you can leave off the table name if the field is unique, but usually leave in for completeness. MySQL website has docs talking about other join types.