0

i am selecting an id from a table and then by id getting name of all members by their ids. Now the problem is that , how to sort name ($uname) alphabetically? It could be simple but i am stuck ..thanks for the help!! Code below -

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

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);

     $uname = $username['0'];


     $Supervisor .="<OPTION VALUE=\"$uname\">".$uname.'</option>';

}

4 Answers 4

3

ORDER BY clause is used for any kind of sorting from database. So change your query in the loop like this:

$query = "SELECT `Name` from `list` WHERE `ID` = '$id' ORDER BY Name ASC  ";

For more information: ORDER BY cluase

Let me know for further help.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but i tried this already but it was not working. Is there any way that we can sort $uname variable?
Make one change in database & query will work. Go to database table column 'Name' and set it's 'Collation' as 'utf8_general_ci'. I think after this query has to work.
1

you can do it in single query, try this one..

$sql= mysql_query("Select DISTINCT Supervisor ID, Name from list ORDER BY Name ASC");

while($row = mysql_fetch_array($sql))
{   
     $uname = $row['1'];
     $Supervisor .="<OPTION VALUE=\"$uname\">".$uname.'</option>';

}

1 Comment

No actually, it will list all the names but i need only names corresponding to Supervisor Id.
0

Use This:-

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

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);
/* Sore name in to an new array */
     $uname[] = $username['0'];


}

Sort your name Array Here Using

sort()

Click Here For Demo of Sort function

 $user_names = sort($uname);

Create Option valus like this

foreach($uname as $name) {
$Supervisor .="<OPTION VALUE=\"$name\">".$name.'</option>';

}

3 Comments

Please Click True if answer is right. and also like the answer.
i can not vote up ur answer because i am new here and don't have reputation.
You can mark this Question as right. By just click True for this you don't need any reputition.
0
SELECT `Name` from `list` WHERE `ID` = '$id' order by `Name` ASC

use order by clause for ascending order and desc for descending order

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.