Jump to content

Join two MySQL tables


jake2624

Recommended Posts

Heyyzarrh, iv been having troubles trying to make it so my PHP script will echo out the username by corresponding the posters ID with the ID in the members table. Heres what iv got so far:

 

<?php
if ($urlid == "") {
}

$sql = mysql_query("SELECT members.username,
posts.mem_id,
posts.post_date,
posts.post
FROM members
JOIN posts
ON members.id = posts.mem_id
WHERE posts.mem_id='$urlid' ORDER BY post_date DESC LIMIT 20");

while ($row = mysql_fetch_array($sql)){	
    echo '<b>' .$row['$username']. ':</b> '.$row['post'].'<br />At: '.$row['post_date'].'<br /><br />';
}
?>

 

Please help!! :S so far only the actual posts data comes out not the username from the table "members"...  :confused:

Link to comment
https://forums.phpfreaks.com/topic/257957-join-two-mysql-tables/
Share on other sites

So the query does work which is good.  I would define the member username separately by doing:

 

$sql = mysql_query("SELECT members.username AS musername,
posts.mem_id,
posts.post_date,
posts.post
FROM members
JOIN posts
ON members.id = posts.mem_id
WHERE posts.mem_id='$urlid' ORDER BY post_date DESC LIMIT 20");

 

And to echo out the members username, just call it with $row['musername']

The problem has nothing to do with the query. If the field did not exist the query would fail. Here is your problem

echo '<b>' .$row['$username']. ':</b> '.$row['post'].'<br />At: '.$row['post_date'].'<br /><br />';

 

Look at the index name that you are using to reference the value ==> $row['$username']

 

I have no idea what the value of the $username VARIABLE is, but I doubt it is the STRING 'username'. Try

echo "<b>{$row['username']}:</b> {$row['post']}<br />At: {$row['post_date']}<br /><br />";

I missed that, good eye.  I had thought the issue might have had to do with there being a username field in both tables causing conflict.

Psycho's solution will definitely fix your issue. you can remove the code that I had told you to add in my first post.

hahaha lol *facepalm*, i went over it so many times an completely missed tht my self lol. thankx man all fixed now :D

 

There are many simple debugging processes that will help you verify/find the errors quite easily. In this situation you know a record was returned. You could have simply done a print_r($row) to verify all the data that was contained in the array.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.