I'm sure that I am doing something fundamentally wrong here; I just cannot get my head around it...

Basically, I have a categories table, a products table, and a category lookup table (catlookup).

I want to randomly generate a "featured" category; pulling the category name and description from the categories table and a random image for that category from one of the products in the product table (the link between the two being the catlookup table).

The problem I have is that some categories do not contain any products, therefore, I do not want to "feature" them. I always want the script to find a category that has at least one product. The following script keeps including categories that don't have products, along with those that do:

//pull a selection of categories and associated images...
 //establish which categories have and entry in the catlookup table and are therefore active and contain products.
 $activecats = @mysql_query("SELECT * FROM catlookup ORDER BY RAND() LIMIT 0,1");
 if(!$activecats) {
  while($active = mysql_fetch_array($activecats)) {
  $cid = $active["cid"];
  $pid = $active["pid"];
   //get all the categories from the categories table...
   $category = @mysql_query("SELECT * FROM categories WHERE id=$cid ORDER BY RAND()");
	if(!$category) {
	while($cats = mysql_fetch_array($category)) {
	 $catid = $cats["id"];
	 $category = $cats["category"];
	 $description = $cats["cat_desc"];
	  //get a random image for the category from one of the products in the category
	  $image_for_cat = mysql_query("SELECT id,thumb,visible,complete FROM products WHERE id=$pid AND thumb != 'thnoimage.gif' AND visible='Y' AND complete='y' ORDER BY RAND() LIMIT 0,1");
	  if(!$image_for_cat) {
	  while($image = mysql_fetch_array($image_for_cat)) {
	  $thumb = $image["thumb"]; 
	  echo("<h4>CAT: ".$category. "</h4><p>Description: ".$description."</p><img src='/images/products/thumbs/".$thumb."' alt='Available now from our current stock' />");
Perhaps I'm just going about it the wrong way?

Cheers in advance...