Problems with Looping

Hello, I’m having some problems with grabbing some information from my database and then looping through it. Here is what I have:
[php]//First My array of letters
$letters = array(‘A’,‘B’,‘C’,‘D’,‘E’,‘F’,‘G’,‘H’,‘I’,‘J’,‘K’,‘L’,‘M’,‘N’,‘O’,‘P’,‘Q’,‘R’,‘S’,‘T’,‘U’,‘V’,‘W’,‘X’,‘Y’,‘Z’);

//Next we have my query
$query = mysql_query(“SELECT id,forename,surname FROM customer ORDER BY surname”) or die(mysql_error());

//We’re going to loop through the array $letters
for($j=0;$j<26;$j++)
{
//echo a header for the letter
echo “

Names Beginning with $letters[$j]

”;
//get the rows from the query
while($row = mysql_fetch_array($query))
{
	//output all rows whose 'surname' starts with said letter
	if($row['surname'][0] == $letters[$j])
	{
		echo "<a href='update.php?id=".$row['id']."'>".$row['forename']." ".$row['surname']."</a>";
		echo "<br />";
	}
}

}[/php]

Now what this code is displaying is the header for the letter A, followed by all the surnames beginning with A. It also shows the headers for B - Z, however it does not show any of the names for the surnames beginning with those letters.

Hi there,

I think your issue should be solved by moving the internal data pointer to the beginning in each loop of the letters:

[php]for($j=0;$j<26;$j++)
{
//make sure we’re starting grabbing data from row 0
mysql_data_seek($query,0);
//echo a header for the letter[/php]

Your line that handles the letters is not correct for PHP…

echo “

Names Beginning with $letters[$j]

”;

Try something like this:

echo “

<a name=names” . $letters[$j] . ">Names Beginning with " . $letters[$j] . “

”;

Think “text that becomes part of the html” and “PHP variable which is NOT text” and it should make sense…

Thanks for the replies, I got rid of the for loop all together and managed to refine it a lot more to my needs, it works fine now.

I completely forgot about the concatenation in the echo, is there any reason as to why I get no errors the way it is just now?

Well, the end of the line gets lost and PHP just doesn’t post it back correctly, so nothing shows up in the HTML once it is rendered into the browser… In PHP you have to either use “try” to catch errors or you have to add error checking code all over the place. Sometimes it is just easier to VIEW-SOURCE on your output page and see what is missing from the “rendered” code…

Good luck… We will mark this thread Solved…

Sponsor our Newsletter | Privacy Policy | Terms of Service