开发者

How to ORDER BY inside a foreach loop?

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.

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.

       // check for existing subusers
   $findsubusers = mysql_query("SELECT * FROM `custportal` WHERE `parentid` = '". $_SESSION['id'] ."'");
   $subusernum = mysql_num_rows($findsubusers);
   if ($subusernum > 0) {
       // subusers present, print them to editable form
       echo "<h2>Edit Existing Users</h2><br />";
       echo "<form method=\"post\" action=\"edit.php\">";
       for ($num=1; $num <= $subusernum; $num++) {
           // print all subusers
           $subuserinfo = mysql_fetch_array($findsubusers);
           echo "<p>Name: ";
           echo "<input type=\"text\" name=\"subusername[]\" value=\"". $subuserinfo['username'] ."\" /></p>";
           echo "<p>Password: ";
           echo "<input type=\"text\" name=\"subuserpass[]\" value=\"". $subuserinfo['password'] ."\" /></p>";
           echo "<input type=\"hidden\" name=\"subuserid[]\" value=\"". $subuserinfo['id'] ."\" />";;
       }
           echo "<input type=\"submit\" name=\"submitchanges\" value=\"Submit Changes\" />";
           echo "</form><br /><br />";
   }

SOLUTION:

$findsubusers = mysql_query("SELECT * FROM `custportal` WHERE `parentid` = '". $_SESSION['id'] ."' ORDER BY username ASC");


You could do something like this:

$names = array()
foreach ($_POST as $name) {
   $names[] = "'" . mysql_real_escape_string($name) "'";
}

$where_in = implode(",", $names);

$query = "SELECT ... WHERE username IN ($where_in) ORDER BY username";
$stmt = mysql_query($query) or die(mysql_error());

Basically, convert your array of usernames into a "where in" clause so a single query fetches ALL the matching records, which can then be ordered within the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜