Reputation: 151
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!
Upvotes: 1
Views: 650
Reputation: 2163
Your problem as already stated is not the JOIN
but an illegal formed SELECT
syntax.
I don't have a great sense for how the join command functions yet, any help would be great!
For starters, here is the manual link for the MySQL SELECT syntax which also shows how to use JOIN.
The JOIN
statement would be used only if you needed to JOIN two or more tables together based upon correlating data. For example. If you had another table named addresses and it had a column relating to the members user_id then you could JOIN the tables together to get all of the addresses for each user. Example code of JOIN:
SELECT
members.*,
addresses.*
FROM
members
JOIN addresses ON
members.user_id=addresses.members_user_id
WHERE
user_id='3'
For more examples and to see how different JOINS such as left, right, inner, outer work see this article explaing sql joins
Upvotes: 1
Reputation: 12139
You are missing a FROM
:
$result = mysqli_query($con,"SELECT members.username FROM members WHERE userid= $userId");
No need for a JOIN
here.
Now to display the name:
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'];
}
/* free result set */
mysqli_free_result($result);
Upvotes: 4
Reputation: 11615
You do not need a JOIN, as the data is available in the same relational row record and table.
You need to
SELECT `username` FROM `members` WHERE `userid` = 3
Assuming Brad's userId is 3.
Upvotes: 3