Hi, Trying to build my own simple-ish forum script, and i want to display 2 forum posts snippets inside each category on the default page. I thought i knew the code for it but when i do

$cat = mysql_query("SELECT * FROM forum_cat")or die(mysql_error());
	$catresult = mysql_num_rows($cat);
	for($count = 1; $count <= $catresult; $count++){
		$rowcat = mysql_fetch_array($cat);
		$get=$rowcat['cat_name'];
		$latest = mysql_query("SELECT * FROM forum_question WHERE category='$get' ORDER BY datetime DESC LIMIT 2")or die(mysql_error());
		$counttresult = mysql_num_rows($latest);
		echo '<div class="box"><div id="title"><div class="icn"><div class="icons2_5"></div></div>'.$rowcat['cat_name'].'<i>'.$counttresult.'</i></div>';
			for($count = 1; $count <= $counttresult; $count++){
				$rowlatest = mysql_fetch_array($latest);
				echo '<div id="block"><div class="title">'.$rowlatest['topic'].'</div>'.substr($rowlatest['detail'], 0, 200).'</div>';
	
			}
				
echo '</div>';
		$cat2=$rowcat['cat_name'];
	}

the code sort of works, but will bring back hundreds of category with blank names, you can see what's happening, but you will need to stop the page loading because it just carries on http://titaniumdesign.gotdns.org/base/forum.php Thanks :)

Recommended Answers

All 2 Replies

Your problem is because you are using $count to "control" both loops. Do NOT use $count for BOTH loops. Use different variables. Try something like $outerCount and $innerCount instead.

Also, they should start at zero (not one) and be "less than" (not "less than or equal to") - ex: for($outerCount = 0; $outerCount < $catresult; ++$outerCount){...} However, you are NOT using that variable for anything other than to iterate through the complete result set. A better approach would be to use a while construct and dump the row result directly into $rowcat for( $ourount = 1; $count <= $catresult

$cat = mysql_query("SELECT * FROM forum_cat")or die(mysql_error());
	while($rowcat = mysql_fetch_assoc($cat)){
		$get=$rowcat['cat_name'];
		$latest = mysql_query("SELECT * FROM forum_question WHERE category='$get' ORDER BY datetime DESC LIMIT 2")or die(mysql_error());
		$counttresult = mysql_num_rows($latest);
		echo '<div class="box"><div id="title"><div class="icn"><div class="icons2_5"></div></div>'.$rowcat['cat_name'].'<i>'.$counttresult.'</i></div>';
			while($rowlatest = mysql_fetch_assoc($latest)){
				echo '<div id="block"><div class="title">'.$rowlatest['topic'].'</div>'.substr($rowlatest['detail'], 0, 200).'</div>';
	
			}
		echo '</div>';
		$cat2=$rowcat['cat_name'];
	}

Thanks for the help, i've decided to stick with my own metho0d with the $count fix.. Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.