I can suggest a bit of streamlining for that by using a do{...}while loop. If you get as far as the loop you know that there is at least one row, so you can wait until the end of the loop to check if there are any more.
function sample_output($results, $query)
{
$sample_size = 5;
echo "<br /><font color=\"red\">The sample query is :</font><br /><br />$query<br /><br />";
echo "<font color=\"red\">The data returned from this query is as follows (up to $sample_size rows):</font><br /><br />";
if(mysql_num_rows($results))
{
echo "\n<table>";
$row = mysql_fetch_array($results, MYSQL_ASSOC);
$array_of_keys = array_keys($row);
echo "<tr>";
foreach($array_of_keys as $key) echo "<th>$key</th>";
echo "</tr>";
$i = 0;
do
{
$i++;
extract($row);
echo "<tr>";
foreach($array_of_keys as $array_key) echo "<td>".$$array_key."</td>";
echo "</tr>\n";
} while(($i < $sample_size) && ($row = mysql_fetch_array($results, MYSQL_ASSOC)));
echo "</table>\n";
}
}
I've added a test to check that there actually are rows returned, but only because I don't see one and an empty result would be buggy - if you did that before calling this function then doing it again here is unnecessary, of course.
Oh, and <font> tags? This is only for local testing, I hope 🙂