Reputation: 1273
I have a simple blog where I'm practicing some php and mysql. I'm trying to display the username of the post author (you know where it says posted by Author). I have two tables blog_members and blog_posts which are related 1 to many so I got a memberID field into the blog_posts. I'm trying to get the username of the member who's the author of the post. I was thinking to do a join or something but I can't figure this out. Here's what I was trying to do but it's not working because I'm sure I'm not using it properly.
$query1 = "SELECT username from blog_members JOIN blog_posts ON memberID = memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
PS: I got it working one way by using SESSION to get the userID but that works only if the user is logged is which is not the case, I want to display the name in any case.
Thanks!
Upvotes: 0
Views: 87
Reputation: 16
JOIN syntax is wrong in your query.
Use following query:
$query1 = "SELECT username from blog_members JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
$result1 = mysqli_query($link, $query1);
$row1 = mysqli_fetch_array($result1);
Upvotes: 0
Reputation: 161
Here is a solution using a simple WHERE condition (same performance Explicit vs implicit SQL joins) :
SELECT a.username FROM blog_members a, blog_posts b WHERE a.memberID = b.memberID
But if you need more information about MySQL Join : https://www.sitepoint.com/understanding-sql-joins-mysql-database/
Hope this helps !
Upvotes: 0
Reputation: 133360
Use inner join this way
And with a proper sanitize use $your_user_id for match
$query1 = "SELECT username
from blog_members
INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID
WHERE blog_posts.memberID = '" .$your_user_id . "';";
Upvotes: 2
Reputation: 852
Try something like this, usng INNER JOIN
:
$query1 = "SELECT blog_members.username FROM blog_members INNER JOIN blog_posts ON blog_members.memberID = blog_posts.memberID ";
reference : http://www.w3schools.com/sql/sql_join.asp
Upvotes: 0