php - 查询多张表及if、elseif、else条件

标签 php mysql

我正在尝试根据查询返回显示不同的消息/按钮。有 3 种不同的情况。

  1. 用户查看他的帐户
  2. 用户评论 friend 帐户
  3. 用户评论非好友账户

所以当用户查看他自己的帐户时,我隐藏了“添加为 friend ”按钮。当他检查非 friend 帐户时,我会显示“添加为 friend ”按钮。当用户检查 friend 帐户时,我想显示该用户是他的 friend 的消息。

这是查询和 if、elseif、else 条件。逻辑有问题,但无法弄清楚到底是什么。

if(isset($_GET['id']) && is_numeric($_GET['id'])){
      $id = $_GET['id']; {     
$result = $pdo->prepare("SELECT usr.*, userFriends.*
                         FROM users usr
                            LEFT JOIN user_friends userFriends
                                ON usr.id = userFriends.friend_id
                         WHERE id = ?                           
                         LIMIT 1");

    $result -> bindParam(1, $id, PDO::PARAM_INT);
    $result -> execute();
    foreach ( $result as $row )
    {
         // some html here
        if($_SESSION['id'] == $row['user_id'])
        { 
            echo ''; 
        } 
        elseif ($id == $row['friend_id'])
        {
            echo ' Already friends ';
        }
        else                            
        { 
            echo ' Add as friend '; 
        }
    }
 }

所以 $_SESSION['id'] 是当前的(登录用户)。

$id 是非好友/好友资料

$row['user_id'] 是表 user_friends 中的当前用户

$row['friend_id'] 是来自 user_friends 表的非好友/好友 ID

最佳答案

你的逻辑有点不对..

您想检查什么?你想检查 $id 是否是 $_SESSION['id'] 的 friend ..所以你应该根据 $id 或 $_SESSION['id'] 进行选择?

if(isset($_GET['id']) && is_numeric($_GET['id'])){
   //the first thing you need to check is that is this you are viewing your own profile by just checking this and without even need to query.
   if($_SESSION['id'] == $_GET['id']){
      echo '';
   } else {
       $id = $_GET['id'];

       $result = $pdo->prepare("SELECT usr.*, userFriends.*
                     FROM users usr
                        LEFT JOIN user_friends userFriends
                            ON usr.id = userFriends.friend_id
                     WHERE **Your ID Column**= ?                           
                     LIMIT 1");

      $result -> bindParam(1, $_SESSION['id'], PDO::PARAM_INT);
      $result -> execute();
      //check if the result return rows?
      // if return rows of data, it's already friend
      // else its not friend yet

      // what's the purpose for this loop then?
      foreach ( $result as $row ){

      }
  }
}

关于php - 查询多张表及if、elseif、else条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33673501/

相关文章:

mysql - 数据库开发 - 总体结构和规划

php - 自动从 mysql 数据库填充数据并插入到新表中

php - 使用多个表上的多个查询从多个表中获取数据

php - 检索并格式化 MySQL 结果列中的所有 hasMany 记录

php - 如何从html删除按钮中删除mysql数据?

php - 我想返回一个用户,其中包含他们推荐的所有人员的列表

Mysql存储过程不以表名为参数

MySQL :- Adding where clause to this query

php - 我该如何解决这个 Solr/MySQL 竞争条件?

php - 我的 mysqli 代码有什么问题?