Need Associated ID Added to a While Loop (php)

Posted by user319361 on Stack Overflow See other posts from Stack Overflow or by user319361
Published on 2010-04-24T00:59:16Z Indexed on 2010/04/24 1:03 UTC
Read the original article Hit count: 273

Filed under:
|
|

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 :)

© Stack Overflow or respective owner

Related posts about php

Related posts about while-loops