views:

99

answers:

4

I want to join 2 tables together but i cant get it to work.

These are the tables:
threads: id, title
posts: thread_id, message

$sql = mysql_query("SELECT threads.id, threads.title
                    FROM threads
                    JOIN posts ON posts.thread_id = threads.id
                    WHERE threads.id = ".intval($_GET['id']));


while ($post = mysql_fetch_assoc($sql))
{
    echo $post['title'];
    echo $post['message'];

}

It gets the title but not the message. I have one assigned to the thread.

+1  A: 

Are there posts with a thread_id that matches $id? Because, if not, that would generate an empty result set.

inkedmn
Try removing the where clause and see if you get any results. If so, the problem is as inkedmn suggested. If not, at least you've just reduced your search space for a solution.
Brian
yes i can get the title from threads
A: 

Can you make it work in MySQL, without the PHP? I rely on phpMyAdmin to troubleshoot queries. Once I get it in MySQL more directly, phpMyAdmin has a "export SQL for PHP" feature.

Smandoli
+3  A: 

You're not selecting posts.message. Change your SQL to this and it may work.

SELECT threads.id, threads.title, posts.message
FROM threads
JOIN posts ON posts.thread_id = threads.id
WHERE threads.id = $id
Rob
thanks that works but not really how i wanted it, i have 2 records and it only loops out one for some reason :/
do they both have the same $id?
tharkun
yes of course <short>
How could two threads possibly have the same ID? Your schema is broken if that is possible.
hobodave
There is no doubt that this is the correct answer.
hobodave
@blue: give us the exact content of your tables
tharkun
A: 

If you want to fetch the posts you might want to do it the other way

SELECT threads.id, threads.title, posts.message
FROM posts
JOIN threads ON threads.id = posts.thread_id
WHERE posts.thread_id = $id
Terw