I am querying a database for a list of part numbers and their respective categories. I’m attempting to run a while over the records and separate each group of part numbers into a div for their respective categories so I can then handle them in css.
For example, the results may consist of
Accessories-Ash_Trays
AT1234
AT2345
Accessories-Coat_Hooks
CH3456
CH4567
CH5678
Accessories-Light_Switch
LS6789
So the output HTML I want:
<div id=“Accessories-Ash_Trays”>
AT1234
AT2345
</div>
<div id=“Accessories-Coat_Hooks”>
CH3456
CH4567
CH5678
</div>
<div id=“Accessories-Light_Switch”>
LS6789
</div>
Here is the code I currently have:
require(“dbconnect.inc”);
// Clear/set the ShowPartList variable
$ShowPartList = “”;
// Query the database for current list of products
$ProductList = "SELECT tbl_catnav.category_set, tbl_products.part_number ";
$ProductList .= "FROM tbl_products ";
$ProductList .= “LEFT JOIN tbl_catnav ON tbl_products.cat_id = tbl_catnav.lastcatid “;
$ProductList .= “ORDER BY tbl_catnav.category_set, tbl_products.part_number;”;
$GetPartList = mysql_query($ProductList);
$NumParts = mysql_num_rows($GetPartList);
$i=0;
$LastCat = “”;
while($i < $NumParts)
{
$CurrentCat = str_replace(” “, “_”,mysql_result($GetPartList,$i,“tbl_catnav.category_set”));
// Test if active category has changed, if so post new category name
if ($CurrentCat != $LastCat) {
$ShowPartList .= “<div id=\“CatTitleDiv\”>”;
$ShowPartList .= “<a href=\“javascript:unhide('” . $CurrentCat . “');\”>” . $CurrentCat . “:</a><br />”;
$ShowPartList .= “<div id=\”” . $CurrentCat . “\” class=\“hidden\”>”;
}
$ShowPartList .= “<a href=index.php?body=prodshow&prodnum=” . mysql_result($GetPartList,$i,“tbl_products.part_number”) . “>” . mysql_result($GetPartList,$i,“tbl_products.part_number”) . “</a><br />”;
if ($CurrentCat != $LastCat) {
// Close both divs opened up for the new Category Section
$ShowPartList .= "</div></div>";
}
$LastCat = $CurrentCat;
$i++;
}
echo $ShowPartList;
I know my problem lies in the if($CurrentCat != $LastCat) near the end of the code, I am just having trouble thinking logically through how to test for it. Basically I know I need to check if it is a new category, if it is then put in the opening DIV statements. Then populate the Product # (using a link so they can go straight to the product info page) then it needs to determine if the closing divs should be there yet, or if there is another part under that same category heading. I’ve thought of testing for that by using something like $i-- or $i++, but the first record (or last) throws an error then because there is no -1 record value and the last record can’t do a ++.
I’m thinking as I write this maybe catching the error from the first pass through, since I know I HAVE to have the opening div commands there. But it seems to me there should be a more elegant solution.
Hopefully I’ve explained this clearly enough.
Greg