SQL - 显示名称而不是ID

时间:2016-08-25 12:55:46

标签: php mysql

我有2张桌子

  

rankID |名称

     
      
  • 1 |新
  •   
  • 2 |学习者
  •   
  • 3 |经历
  •   
  • 4 |亲
  •   

另一个包含所有用户信息,密码和内容

  

id |用户名| rankID

     
      
  • 1 |你好| 3
  •   
  • 2 |嘿| 3
  •   

我到目前为止所以我可以显示他们的排名,但我想显示排名。我怎样才能做到这一点?我已经尝试了很多东西但是我不太擅长sql和它的php部分。

这是我用来显示排名编号的代码

//Get rankID
$query = "SELECT rankID FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];

并显示等级编号:

Rank: <?php echo $rank; ?>

7 个答案:

答案 0 :(得分:2)

简单JOIN查询: -

"SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'"

然后: -

$query = "SELECT rank.name as rank_name,users.rankID as rankID from users LEFT JOIN rank ON rank.rankID = users.rankID WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);

执行: -

$rank = $row['rankID'];
$rank_name = $row['rank_name'];

Rank: <?php echo $rank; ?>
RankName: <?php echo $rank_name; ?>

或者

$rank_data = $row;
Rank: <?php echo $rank_data['rankID']; ?>
RankName: <?php echo $rank_data['rank_name']; ?>

不是: - 其他程序员在评论和回答中列出了许多其他可能的方式。

答案 1 :(得分:0)

//获取数据

$query = "SELECT rankID, name FROM users WHERE id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rankID'];
$rank = $row['name'];

并显示数据:

Rank: <?php echo $rank; ?>
Name: <?php echo $name; ?>

答案 2 :(得分:0)

希望这对你有用。

$query = "SELECT rankID FROM users WHERE id = '".$userId."'";
$result = $conn->query($query);
$count = $result->num_rows;
if($count==0)
{
   return false;
}
else
{
     $rows=[];
     while($row = $result->fetch_assoc())
     {
        $rows[] = $row;
     }
     return $rows;
}

答案 3 :(得分:0)

请使用以下代码

$query = "SELECT name FROM users as u JOIN rank as r ON r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$name = $row['name'];


Name: <?php echo $name; ?>

答案 4 :(得分:0)

试试这个:

//Get rankID
$query = "SELECT rankID, rank.name AS rank_name FROM rank, users WHERE id = '$userId' and users.rankid = rank.rankid";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];
echo $rank;

答案 5 :(得分:0)

当您想从两个不同的表中获取数据时。您需要加入查询。 以下是您的查询,它将明确解决您的问题:

$q="select a.name,b.rankID from rankname as a INNER JOIN user as b
ON a.rankID = b.rankID";

有关如何加入两个表的更多信息,请参阅:http://www.tutorialspoint.com/sql/sql-using-joins.htm

希望这会对你有所帮助。

答案 6 :(得分:0)

请试试这个

//Get rankID
$query = "SELECT r.name as rank_name FROM rank as r inner join users as u on r.rankID = u.rankID WHERE u.id = '$userId'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rank = $row['rank_name'];

echo 'Rank: '. $rank;