PHP limit *file* results not *search* results

I have a dynamic gallery that pulls info from a database (name, title, description) and then outputs those along with thumbnail pics to the html.
Here is the meat:

$result = mysql_query("SELECT * FROM gallery");
  while ($myrow = mysql_fetch_array($result)) {
  	$name = $myrow["name"];
  	$title = $myrow["title"];
  	$description = $myrow["description"];
  	$dir = "/home/marchlew/public_html/images/".$name."/thumbs"; 
  	$handle = opendir($dir);
  	printf("<p>%s</p>
<p>%s</p>", $title, $description);
  ?>
  	<table border="0" align="center" cellpadding="0" cellspacing="0">
  	   <tr align="center">
  <?PHP
  
  		  while (false !== ($file = readdir($handle))) {
  			 if ($file != "." && $file != "..") {
  				 //build the table rows
 				 printf("<td><a href=\"javascript:popImage('images/%s/pics/%s','%s')\"><img src=images/%s/thumbs/%s hspace=5 border=0 ></a></td>
", $name, $file, $title, $name, $file);
  			 }
  		  }
  ?>
  	  </tr>
  	</table>
  

It does just what it should, but I want it to work a little differently. When the php searches through the directory, I want to limit the results to 5 files and then start with a new table for the rest of the pics.
Something like:


  ...get the db stuff
  ***
  	<table border="0" align="center" cellpadding="0" cellspacing="0">
   	   <tr align="center">
   <?PHP
   
   		  while (false !== ($file = readdir($handle))) {
   			 if ($file != "." && $file != "..") {
   				 //build the table rows
 				 printf("<td><a href=\"javascript:popImage('images/%s/pics/%s','%s')\"><img src=images/%s/thumbs/%s hspace=5 border=0 ></a></td>
", $name, $file, $title, $name, $file);
  
  ...start counting files
  
   ...when we get to 5, go back to *** and start a new table
  
   			 }
   		  }
   ?>
   	  </tr>
   	</table>
   

I can do the file count, but I don’t know how to get it to go back and start a new table, or how to get it to pick up with the file it left off with.
To see it in practice, visit http://marchlewskiguitars.com/gallery.php

Thanks,
-Joshua