tags:

views:

92

answers:

3

I have the following table:

Comments
--------
id      PK
cid     
content 
uid
comment

If the content is image /i want it to print ?imgID=$cid and get the data from the row title from the table images and if it's a thread I want it to print ?threadID=$cid and get the title from the table threads and so on. How should I do this?

<h3>Latest comments</h3>
<?php 

$rs = mysql_query("
  SELECT * 
  FROM comments 
  LEFT JOIN threads 
    ON threads.id = comments.cid 
  WHERE comments.uid = $id
");
while ($row = mysql_fetch_assoc($rs)) {
 echo $row['title'];
}
+2  A: 
 while ($row = mysql_fetch_assoc($rs)) {
   if($row['content'] == "image") {
        echo "?imgID={$cid}";
        $title = mysql_fetch_assoc(mysql_query("SELECT title from images WHERE id = '$cid'");
   } elseif ($row['content'] == "thread") {
        echo "?threadID={$cid}";
        $title = $row['title']; // Will only work as long as there is no title field in comments, oherwise use threads.title
   }
 }
 echo $title;

There you go. The curly brackets around the $cid aren't strictly nessecary, but they help avoid issues where if you are trying to print text afterwards, and it reads the variable name as something else.

Macha
A: 

I would recommend one of these resources as a starting point.

jcinacio
A: 
$q="SELECT c.id, c.cid, c.content, c.uid, c.comment,
    COALESCE(t.title,i.title) AS the_title
    FROM comments c LEFT JOIN threads t ON (c.cid=t.id AND c.content='thread')
                    LEFT JOIN images i ON (c.cid=i.id AND c.content='image');

The above combines your two queries together and puts the title attribute in one column.

dnagirl
+1 for inventive solution. -1 for the fact that it's rare (first time I've ever seen COALESCE), and would confuse a newbite.
Macha
COALESCE takes the first non-NULL value in its argument list and outputs it. It is very useful if your query has several fields that are mutually exclusive or need to be chosen by a particular order of precedence.
dnagirl