bcraig Posted December 14, 2007 Share Posted December 14, 2007 How do i get a list/menu to display records form DB depending on the selection on a previous list/menu? The first list has main categories and the second list has sub categories conected to the main Heres a small example of my db table: categoies cat_id | parent_id | cat_name 1 0 MainOne 2 0 MainTwo 3 1 SubOneA 4 1 SubOneB 5 2 SubTwoA 6 2 SubTwoB this is what i have for the first list <?php $mysqli = mysqli_connect("localhost", "root", "", "jobsnz"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $sqlcat_drop = "SELECT cat_name FROM categories WHERE parent_id = 0"; $rescat_drop = mysqli_query($mysqli, $sqlcat_drop); ?> <select name="categories"> <?php if ($rescat_drop) { while ($newArray = mysqli_fetch_array($rescat_drop, MYSQLI_ASSOC)) { $catname = $newArray['cat_name']; echo "<option>".$catname."</option>"; } } else { printf("Could not retrieve records: %s\n", mysqli_error($mysqli)); } ?> </select> Quote Link to comment Share on other sites More sharing options...
KrisNz Posted December 14, 2007 Share Posted December 14, 2007 1. Change your first query so that it gets the cat_id as well as the category name. 2. Change this $catname = $newArray['cat_name']; echo "<option>".$catname."</option>"; to something like $categoryId = $newArray['cat_id']; echo "<option value="$categoryId">$catname</option>"; 3. Set up a condition in the appropriate place to test if your categories drop down has been posted back. (I presume you've got that select inside a form that can be submitted!). if (isset($_POST['categories']) and intval($_POST['categories']) > 0) { $parentId = intval($_POST['categories']); //run query to get records where parent_id = $parentId // so if user chooses MainOne, $parentId = 1 and the resulting query should return records 3 & 4 } 4. display new records in much the same way you displayed the first set.... Quote Link to comment Share on other sites More sharing options...
bcraig Posted December 14, 2007 Author Share Posted December 14, 2007 this only brings the sub categories up after i post with a submit button. Is it possible for the main categories list to update the sub list instantly when a main category is selected? or is that beyond php? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.