Contact for Expert ServicesAdvertise with Ecomspark.

How to alphabetical sort mysql query field variable in PHP?

Today  i was working on a code and find some difficulty while doing it. So i thought, i should share this with all of you.

Actually, i want to alphabetical sort mysql query filed value variable.

Lets start it with a code –

 $sql= mysql_query("Select DISTINCT(`Supervisor ID`) from `list` ");

In above query, i am selecting unique supervisor id from table list. Actually, i need names who are Supervisors and i have only supervisor ids.

In below code, i got the ids of Supervisors the i again fire the query to find the Name who are Supervisors. Now,
$username[0] field contains the names of all Supervisors. But i was stucked, how to sort this $username[0] variable that contains all names.

So, i sort name into a new array $uname[] .

while($row = mysql_fetch_array($sql))
     $id = $row['Supervisor ID'];
     $query = "SELECT `Name` from `list` WHERE `ID` = '$id'  ";
     $name = mysql_query($query);

     $username = mysql_fetch_array($name);
/* Sort name in to an new array */
     $uname[] = $username['0'];

Now, i used the sort() function to sort array.

$user_names = sort($uname);

Then, i created all the options values like this –

foreach($uname as $name) {
echo $name;

This will print all names who are Supervisors in alphabetical order. The main work was here to sort name into new array and then sort names.


Add a Comment

Your email address will not be published. Required fields are marked *

Translate »