虽然Loop上只有特定的id

时间:2013-01-24 08:17:13

标签: php loops while-loop

<?php

class Friends {
  public function __construct() { 
    global $DB, $name, $f_name;
    $name = $_SESSION['name'];
    if (isset($_POST['submitted'])) {
      $f_name = mysql_real_escape_string($_POST['f_name']);
    }
  }

  public function AddList() {
    global $DB,$name;
    echo "<center>";
    $result = $DB->query(
        "SELECT * FROM friends WHERE user_name!='{$name}' AND friend_name!='{$name}' "
    );

    while($row = mysql_fetch_array($result)) {
      echo "<form method='post'>";
      echo '<input type="hidden" value=' . $row['user_name'] . ' name="f_name"</th> ';
      echo '<tr>';

      echo '<th><b><font color="#663300">' . $row['user_name'] . '</font></b></th>';

      $this->auth();
      echo "</form>";
      echo "</tr>";
      echo "</tr>";
    }

    echo "</table>";
    echo "</center>";
  }


  public function auth() {
    global $name,$f_name,$DB;
    $authprove = $DB->query("SELECT * FROM approval WHERE sender_id='{$name}'");

    if (mysql_num_rows($authprove) > 0) {
      echo '<th><b>Approving...</th>';
    } else {
      echo '<th><b><input type="submit" name="submitted" value="Add"></th>';
    }
  }
}

$F= new Friends();

?>

有点解释:

是否可以只输出一个特定的ID来输出Approving和另一个输出Add。

喜欢这个

表(批准)时:

---- sender_id || receive_id

---- Admin ||旅客

输出Friends.php:

----加上好友:

----访客 - &gt;等待批准

---- Guest2 - &gt;加为好友

---- Guest3 - &gt;加为好友

1 个答案:

答案 0 :(得分:0)

您正在以非常低效的方式执行任务:如果您有N个用户,您将运行N + 1个查询。您可以使用JOIN通过单个查询完成此操作。在这种情况下,你只需一个循环就可以满足你的需求。

类似的东西:

$query = "
    SELECT 
      f.id, 
      f.user_name, 
      f.fullname, 
      a.status 
    FROM 
      friends f
      LEFT OUTER JOIN approval a ON (f.id=a.sender_id) 
    WHERE 
      user_name!='{$name}' 
      AND friend_name!='{$name}'
";


$result = $DB->query( $query );
while( $row = mysql_fetch_array( $result ) ) {
  echo $row['f.fullname'];
  if ( $row['a.status'] == 'approved' ) echo "Add as Friend";
  else echo "Add as Friend";
}