Code: Select all
<?php
foreach ( range ('A' ,'Z' ) as $letter ) {
echo '<tr><td colspan="2" bgcolor="#ccc"><b>- '.$letter.' -</b></td></tr>';
$result=mysql_query("SELECT * FROM $table ORDER BY last ASC");
while ($row=mysql_fetch_array($result)) {
$first=$row['first'];
$last=$row['last'];
$ext=$row['ext'];
if (substr ($last ,0,1)==$letter) {
echo '
<tr><td>'. $last .', '.$first.'</td>
<td align="center">'.$ext.'</td></tr>';
} // end of if routine
} // end of while routine
} // end of foreach routine
?>My question about efficiency is that my current code queries the database 26 times -- once for each letter of the alphabet. There has to be a better method.
Originally, I had the mysql_query statement outside of all the loops. I never quite got what I wanted even when I nested the foreach loop inside the while loop. The output was correct, but only for the last names beginning with A. No other names appeared even though the rows with the letters of the alphabet did show up correctly. I figured that after the first cycle through, the pointer was at the end of the $row array and that's why only the A names showed up. To fix that problem, I tried using the reset function for $row as well as $results.
Code: Select all
<?php
reset ($row);
?>Like I said, I have something that works, so this post simply strives for a more efficient code. Can any one give a hint as to where and/or why I went wrong?
Thanks!