I’ve got this code and I don’t know how to order my query
function get_All_Categories(){
//new instance of mysqli
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
//if it doesn't work give an error
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$queryCats ="SELECT Catid, Catname
FROM ProductCats
ORDER BY Catid";
$querySubCats ="SELECT Subcatname, Parentid
FROM ProductSubCats, ProductCats
WHERE ProductSubCats.Parentid = ProductCats.Catid
ORDER BY Subcatname;";
if ($catResults = $mysqli->query($queryCats)){
if (!$catResults) {
echo 'Could not run query: ' . mysql_error();
exit;
}
else{
$subCatResults = $mysqli->query($querySubCats);
}
while ($rows = $catResults->fetch_assoc()) {
echo '<div class = "categoryCluster">';
echo '<a href="../index.php?Cat='.$rows["Catname"].'">'.$rows["Catname"].'</a>';
echo '<br>';
while($rowsSub = $subCatResults->fetch_assoc()){
echo '<div class="subCategoryCluster">';
echo ' '.'<a href="../index.php?Cat='.$rows["Catname"].'&'.'Subcat='.$rowsSub["Subcatname"].'">'.$rowsSub["Subcatname"].'</a>';
echo '<br>';
echo '</div>';
}
echo '</div>';
}
}
$mysqli->close();
}
Which displays this output:
Header 1
Subcat 1
Subcat 2
OtherSubcat 1
Header 2
Header 3
Header 4
Header 5
Header 6
But my problem is that subcat 1 and subcat 2 have the parentid of 1, which conforms to header 1, however othersubcat 1 has the parentid of 5. Which actually conforms to header 5.
Yeh in my loop it is displaying right after the other 2.
Now I know why this is wrong, it is because the while loop in the while loop is ordering it to appear last, and sticking it in there.
But I have absolutely no idea how to rework this so that it would display:
Header 1
Subcat 1
Subcat 2
Header 2
Header 3
Header 4
Header 5
OtherSubcat 1
Header 6
Sample table:
> ProductSubCats
> Subcatid | Subcatname | Parentid
> 1 | Subcat 1 | 1
> 2 | Subcat 2 | 1
> 3 | Othersubcat 3 | 5
>
>
>
> ProductCats
> Cat id | Catname
> 1 | Header 1
> 2 | Header 2
> 3 | Header 3
> 4 | Header 4
> 5 | Header 5
> 6 | Header 6
Thank you for your help
For what you are trying to do, following off what @Pasha Bitz said.
Try the following:
That should resolve this for you, study the code so you understand what is going on here.