views:

50

answers:

1

Been trying to get my head around while loops for the last few days but the code seems very inefficient for what Im trying to achieve. I'm assuming I'm overcomplicating this though nothing I've tried seems to work.

Each topic in my forum can have related topic IDs stored in a seperate table. A post ID is also stored in this table, as that specific post references why they are considered related.

DB Table contains only: topic_id, related_id, post_id

// Get related IDs and post IDs for current topic being viewed
$result = $db->query('SELECT related_id, post_id FROM related_topics WHERE topic_id='.$id.'');
    // If related topics found, put both of the IDs into arrays
    if ($db->num_rows($result)) {
        while($cur_related = mysql_fetch_array($result)){
            $reltopicarray[] = $cur_related['related_id'];
            $relpost[] = $cur_related['post_id'];
        }

        // If the first array isnt empty, get some additional info about each related ID from another table
        if(!empty($reltopicarray)) {
            $pieces = $reltopicarray;
            $glued = "\"".implode('", "', $pieces)."\"";
            $fetchtopics = $db->query('SELECT id, subject, author, image, etc FROM topics WHERE id IN('.$glued.')');
        }

        // Print each related topic         
        while($related = mysql_fetch_array($fetchtopics)){ ?>

    <a href="view.php?id=<?php echo $related['id']; ?>"><?php echo $related['subject']; ?></a> by <?php echo $related['author']; ?>

    // Id like to show the Post ID below (from the array in the first while loop)
    // The below link doesnt work as Im outside the while loop by this point.
    <br /><a href="view.php?post_id=<?php echo $cur_related['post_id']; ?>">View Relationship</a>

<?php } ?>

The above currently works, however I'm trying to also display the post_id link below each related topic link, as shown above.

Would be greatful if someone can lend a hand. Thanks :)

A: 
SeanJA
This assumes that there is always a $relpost for each of the topics.
SeanJA
The stuff after the edit is a better answer than the first one...
SeanJA
Thanks for the effort but the single query version is similiar to what I originally attempted. Unfortunately it always grabs the same topic subject (that declared in the WHERE id=). I first need to get the related IDs in order to then get the correct subject. I'm going to try your original code shortly, thanks :)
Ryan
I couldn't get the single query to work (though I may revisit the idea later) however your answer set me on the right path and definately helpful. I've added a join to the second query to grab the related post_id and working as planned :)
Ryan