如何在foreach循环中进行ORDER BY?

时间:2011-03-18 22:37:27

标签: php mysql foreach sql-order-by

背景:控制面板允许具有特定“角色”(读取:排名)的用户创建和维护子用户。有一个foreach()循环,它将与其帐户关联的所有子用户显示在文本字段中,以便于编辑。虽然它仍处于开发阶段,但我仍然试图按顺序查询,以便子用户按创建顺序显示。

我意识到它不会对它们进行排序的原因是由于查询每个循环只选择一个条目,因此无需排序。由于'username'字段中的数组值,查询需要在循环内部,因为它在循环的每次传递中都是动态的。

       // 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 />";
   }

解决方案:

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

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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

基本上,将您的用户名数组转换为“where in”子句,以便单个查询获取所有匹配的记录,然后可以在查询中对其进行排序。