title: How to ORDER BY inside a foreach loop?
body: <p>Background: Control panel that lets users with a certain "role" (read: rank) create and maintain sub-users. There is a foreach() loop that displays all the sub-users associated with their account into text fields for easy editing. Though it is still in development, I am stuck trying to order the query so the sub-users display in the order they were created.</p>
  
  <p>I realize the reason it won't order them is due to the query only selecting one entry per loop, therefore there is nothing to sort. The issue arises from the query needing to be inside the loop due to the array value in the 'username' field, as it is dynamic on each pass of the loop.</p>
  
  <pre><code>       // check for existing subusers
     $findsubusers = mysql_query("SELECT * FROM `custportal` WHERE `parentid` = '". $_SESSION['id'] ."'");
     $subusernum = mysql_num_rows($findsubusers);
     if ($subusernum &gt; 0) {
         // subusers present, print them to editable form
         echo "&lt;h2&gt;Edit Existing Users&lt;/h2&gt;&lt;br /&gt;";
         echo "&lt;form method=\"post\" action=\"edit.php\"&gt;";
         for ($num=1; $num &lt;= $subusernum; $num++) {
             // print all subusers
             $subuserinfo = mysql_fetch_array($findsubusers);
             echo "&lt;p&gt;Name: ";
             echo "&lt;input type=\"text\" name=\"subusername[]\" value=\"". $subuserinfo['username'] ."\" /&gt;&lt;/p&gt;";
             echo "&lt;p&gt;Password: ";
             echo "&lt;input type=\"text\" name=\"subuserpass[]\" value=\"". $subuserinfo['password'] ."\" /&gt;&lt;/p&gt;";
             echo "&lt;input type=\"hidden\" name=\"subuserid[]\" value=\"". $subuserinfo['id'] ."\" /&gt;";;
         }
             echo "&lt;input type=\"submit\" name=\"submitchanges\" value=\"Submit Changes\" /&gt;";
             echo "&lt;/form&gt;&lt;br /&gt;&lt;br /&gt;";
     }
  </code></pre>
  
  <p>SOLUTION:</p>
  
  <pre><code>$findsubusers = mysql_query("SELECT * FROM `custportal` WHERE `parentid` = '". $_SESSION['id'] ."' ORDER BY username ASC");
  </code></pre>