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!

1
  • you are missing a FROM clause in your query statement. Can you update your question with the name and structures of your tables ? Commented Oct 10, 2013 at 16:18

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly! Thanks very much. I was confusing the need for join with something else I had attempted a while back. Much appreciated!
@slycat see my answer below to understand more about what joins are and how they work so there will not be confusion next time.
3

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.