Query/Loop questions - PHP Noob - Coldfusion Expert
Posted: Sun Feb 13, 2011 12:35 am
Coming from a long Coldfusion background, I'm having a little trouble grasping some hopefully basic stuff. Having problems with placing a 2nd query inside a loop. Or, having problems grouping output, depending on how you look at it.
So, here's what I've got:
1. 2nd query isn't displaying any results.
2. If I change "$row[id_cat]" to "10" (a known ID), I'll get results - so I must have a syntax error because the 2nd query WILL work if given a good ID number.
What do I have wrong?
------------------------------------------------
Gotta be a better way though. In Coldfusion, I could just run a single query on the two tables, and then GROUP the output with CFOUTPUT tags
Giving me the desired output:
MAIN STUFF
sub stuff 1
sub stuff 2
sub stuff 3
MORE STUFF
sub stuff 1a
sub stuff 2a
sub stuff 3a
Look how clean and simple that is! For the life of me, I can NOT find a way to do it in PHP, thusly the query inside the loop - which will also work in Coldfusion, but isn't the optimal way of doing things.
Advise please?
So, here's what I've got:
Code: Select all
QUERY IN A LOOP
<?php
// FIRST QUERY
$result = mysql_query("SELECT id_cat, link_cat FROM link_categories ORDER by link_cat_ord") or die(mysql_error());
?>
<!--- BUNCH OF STUFF SNIPPED OUT HERE --->
<?php
// LOOP HERE - SHOWS CATEGORY WITH H1 TAG
while ($row = mysql_fetch_assoc($result)) {
echo "<h1>".$row['link_cat']."</h1>";
// 2ND QUERY HERE, USES RESULTS FROM FIRST QUERY TO PULL UP RELATED RECORDS AND DISPLAY UNDER THE MAIN CATEGORIES
$result2 = mysql_query("select link_name, cat_id from link_urls where cat_id = $row[id_cat]") or die(mysql_error());
while ($row = mysql_fetch_assoc($result2)) {
echo $row['link_name'];
echo "<br />";
}
}
?>
2. If I change "$row[id_cat]" to "10" (a known ID), I'll get results - so I must have a syntax error because the 2nd query WILL work if given a good ID number.
What do I have wrong?
------------------------------------------------
Gotta be a better way though. In Coldfusion, I could just run a single query on the two tables, and then GROUP the output with CFOUTPUT tags
Code: Select all
<cfoutput query="myquery" group="mycategories">
<h1>#mycategories#</h1>
<cfoutput>
#allMySubCategories#<br />
</cfoutput>
</cfoutput>
MAIN STUFF
sub stuff 1
sub stuff 2
sub stuff 3
MORE STUFF
sub stuff 1a
sub stuff 2a
sub stuff 3a
Look how clean and simple that is! For the life of me, I can NOT find a way to do it in PHP, thusly the query inside the loop - which will also work in Coldfusion, but isn't the optimal way of doing things.
Advise please?