Order by clause in MySQL is not working inside a foreach loop
===

I'm trying to get the profiles names which are assigned to a specific subcategory 
with id=9. When I run the code below, I get the profiles that I want but for some 
reason the ORDER BY clause in the foreach loop doesn't sort them by their name 
alphabetically. Instead they are ordered in the same way they are ordered inside the 
'profiles' field in 'subcategories' table (the IDs for the profiles are comma separated). 
For example if in subcategories['profiles'] I have ',5,1,2' the profiles names will be displayed
in the following order:

1. Profile with ID=5 
2. Profile with ID=1
3. Profile with ID=2
    
I'm using the explode() function to get the ID for each profile inside the 'subcategory' 
table and then use that ID to retrieve their information from the 'profile' table using 
a query inside the foreach loop.

Am I missing anything here? Thanks for your help.

Here's my code:
           
    <?php
    $subcategories=mysql_query("select * from subcategories where id='9'");

    while ($subcategories = mysql_fetch_array($subcategories)) 

    {
	 $profiles = $subcategories['profiles'];
	 $profiles = explode(',', $profiles);
			       
           foreach ($profiles as $p)
	       {
             $all_places = mysql_query("select * from profile where id='$p' and active='1' order by name asc");
		
               while ($profile = mysql_fetch_array($all_places)) 
               {
				
                   echo $profile['name']; 		            
            
               }
		
	       }
			
    }
    ?>