1

我的代码有效,但是由于它获取组代码的方式,我无法按 ID 对数据进行排序。这是代码:

function displayOverview(){
   global $database;
   global $session;
   $q = "SELECT username, group_code "
   ."FROM classes WHERE username = '".$session->username."'";
   $result = $database->query($q);
   /* Error occurred, return given name by default */
   $num_rows = mysql_numrows($result);
   if(!$result || ($num_rows < 0)){
      echo "Error displaying info";
      return;
   }
   if($num_rows == 0){
      echo '<div id="container"><div id="float_left"><img src="profile_pics/default.gif" class="image3" width="50" height="50" border="0"></div>
        <div id="float_right"><div id="container2"><div class="bubble">
        <p class="user_name"></p>
        <p class="time">Error Name | <?php echo date("F j, Y, g:i a"); ?></p>
        <p class="post">Error messages.</p>
        <!-- <p class="attachments"><img src="images/attachment.png" width="20" height="20"><b>Attatchmentments</b><br></p> -->
        </div></div></div></div>';
      return;
   }
   /* Display table contents */
   for($i=0; $i<$num_rows; $i++){
       $group_code = mysql_result($result,$i,"group_code");
   $q2 = "SELECT id, username, post, date, group_code, type, attachment_1, attachment_2 "
   ."FROM posts WHERE group_code = '".$group_code."'";
   $result2 = $database->query($q2);
   /* Error occurred, return given name by default */
   $num_rows2 = mysql_numrows($result2);
   for($i2=0; $i2<$num_rows2; $i2++){
       $uname2  = mysql_result($result2,$i2,"username");
       $post = mysql_result($result2,$i2,"post");
       $type = mysql_result($result2,$i2,"type");
      $userinfo2  = $database->getUserInfo2($uname2);
      $userinfo3  = $database->getUserInfo3($uname2);
      $full_name = $userinfo2['full_name'];
      $profile_img = $userinfo2['profile_img'];
   }
  }
}

我完全被卡住了,是否有另一种方法来检索组代码然后调用 MYSQL 数据库并找出用户所在的组并只返回这些组的帖子

4

2 回答 2

2

您可以在一个查询中执行此操作,方法是JOIN像这样输入两个表:

SELECT
  c.username,
  c.group_code,
  p.id,
  p.post, 
  p.date,
  p.type,
  ...
FROM classes AS c
INNER JOIN posts AS p ON c.group_code = p.group_code
WHERE c.username = ...
ORDER BY p.Id;
于 2013-05-18T23:16:03.720 回答
1

我不完全理解您的问题,但您可以通过添加以下内容对 SQL 进行排序:

... ORDER BY field [ASC/DESC]

或者你可以在 PHP 中使用sort进行排序。

于 2013-05-18T23:16:02.497 回答