Sorting alphabetically

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jb
Forum Newbie
Posts: 5
Joined: Tue Mar 02, 2004 9:11 am

Sorting alphabetically

Post by jb »

I am successfully returning results from my database using the following code, but I want the results to be listed alphabetically by surname.

I have tried to add ORDER BY surname to $query without success.

I am now stuck as I'm not sure if the SORT function should be used somewhere in the while loop.

Any help would be much appreciated......

$query = "SELECT name.surname, name.forename, name.extention

FROM name

WHERE name.departmentID = ".$dept ;

$result = mysql_query($query);


while ($record = mysql_fetch_assoc($result)) {

while (list ($fieldname, $fieldvalue)=each($record)){
echo "$fieldvalue ";
}
echo"<BR>";
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

This should work:

Code: Select all

$query="SELECT surname, forename, extenction FROM name WHERE departmentID = ".$dept." ORDER BY 1";
jb
Forum Newbie
Posts: 5
Joined: Tue Mar 02, 2004 9:11 am

Post by jb »

Thanks very much.

It's interesting it sorts from 1 and not 0.

Do you have any suggestions as to the best approach for formatting the results?

I want to put a comma after the surname to make it more readable.
Because the whole result is being returned by $fieldvalue I'm not sure what approach I should be looking towards.

Thanks again.
User avatar
delorian
Forum Contributor
Posts: 223
Joined: Sun May 04, 2003 5:20 pm
Location: Olsztyn, Poland

Post by delorian »

There are as many good suggestions as you can possibly imagine.

If you want to pot comma after the surrname try this:

Code: Select all

while ($record = mysql_fetch_assoc($result)) { 
foreach($record as $fname => $fvalue) {
        echo $fvalue.($fname == 'surname' ? ", ":"");
} 
echo"<br />";
}

BTW: Read this ->viewtopic.php?t=21171
jb
Forum Newbie
Posts: 5
Joined: Tue Mar 02, 2004 9:11 am

Post by jb »

Many thanks!
Post Reply