Need Associated ID Added to a While Loop (php)
Been trying to get my head around while loops for the last few days but the code seems very inefficient for what I'm trying to achieve. I'm assuming I'm over-complicating this though nothing I've tried seems to work.
Each topic in my forum can have related topic IDs stored in a separate 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 a开发者_JS百科s 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.
if you change the second while loop to something like this:
<?php
$i = 0;
while($related = mysql_fetch_array($fetchtopics)){
//show view link
// [...]
//show the view related link
?>
<a href="view.php?post_id=<?php echo $relpost[$i]['post_id']; ?>">View Relationship</a>
<?php
//increment the i so that you can get the next post in the next iteration of the loop
$i++;
}
?>
[sidenote] You probably should not be doing database queries in the same location you are generating the html for future-you's sanity. [/sidenote]
[edit]
You could also do it all as one query:
SELECT related_topics.related_id,
related_topics.post_id,
related_topics.topic_id,
topics.subject,
topics.author,
topics.image,
topics.etc
FROM related_topics
LEFT JOIN topics ON topics.id = related_topics.topic_id
WHERE topic_id= $id
Then you only have to loop through it once for all of the links.
精彩评论