0

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!

Ovidiu G
  • 1,253
  • 5
  • 25
  • 47

4 Answers4

2

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 . "';";
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

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

Gabriel Bourgault
  • 842
  • 11
  • 22
0

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

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 !

Community
  • 1
  • 1
Alex
  • 151
  • 1
  • 6