mysql - How to alphabetical sort php while loop variable?

706

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

}
341

Answer

Solution:

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.

60

Answer

Solution:

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

}
689

Answer

Solution:

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

}
191

Answer

Solution:

SELECT `Name` from `list` WHERE `ID` = '$id' order by `Name` ASC

useorder by clause for ascending order and desc for descending order

People are also looking for solutions to the problem: php form action link

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.