1

New to php but learning a lot. Relatively simple question that I believe uses the JOIN command. In my code...

This gets and prints out the current session user:

$userId = $_SESSION['user_id'];
echo $userId;

But user_id is just a number in my members table, so that will print out "3" or some such. In the same members table, there is a column called 'username' where 3 (id column) is associated with 'Brad' (username column.)

What would the echo command be to get it to print Brad? I tried something like

$actualname = mysqli_query($con,"SELECT members.username JOIN members on userid=members.id"); 

echo $actualname;

I don't have a great sense for how the join command functions yet, any help would be great!

4

3 回答 3

4

您缺少一个FROM

$result = mysqli_query($con,"SELECT members.username FROM members WHERE userid= $userId"); 

这里不需要JOIN

现在显示名称:

while ($row = mysqli_fetch_assoc($result)) {
   echo $row['username'];
}

/* free result set */
mysqli_free_result($result);
于 2013-10-10T16:20:16.160 回答
3

您不需要 JOIN,因为数据在同一个关系行记录和表中可用。

你需要

SELECT `username` FROM `members` WHERE `userid` = 3

假设 Brad 的 userId 为 3。

于 2013-10-10T16:19:46.587 回答
1

如前所述,您的问题不是非法的语法,JOIN而是非法的SELECT语法。

我对 join 命令的功能还不太了解,任何帮助都会很棒!

对于初学者,这里是 MySQL SELECT 语法的手动链接,它还显示了如何使用 JOIN。

只有当您需要根据相关数据将两个或多个表连接在一起时,才会JOIN使用该语句。例如。如果您有另一个名为地址的表,并且它有一个与成员 user_id 相关的列,那么您可以这些表连接在一起以获得每个用户的所有地址。JOIN 示例代码:

SELECT
  members.*,
  addresses.*
FROM
  members
  JOIN addresses ON
    members.user_id=addresses.members_user_id
WHERE
  user_id='3'

有关更多示例并了解不同的 JOINS(例如左、右、内、外)如何工作,请参阅这篇文章解释 sql 连接

于 2013-10-10T16:30:25.700 回答