Creating forum with all topics and posts on same page
Posted: Sun Nov 15, 2009 10:04 pm
I have successfully created a forum where the topics are listed on one page and users can click on the topic to be redirected to another page with all relevant comments on the particular topic. However, I am now attempting to set it up so that all topics will be listed on the page and all comments will be listed with their respective topic so that the user doesn't have to click a link to a different page to see them. As you can see, I created a query to get all of the topics from their MySQL table. I have a for loop which writes all the topics correctly. I have created a second query to access the comment table and tried nesting another for loop that lists all comments for a particular topics (by matching all items in the comment table that have a given topic-ID). This is where my code doesn't work, although it doesn't have any problems when I execute it to display my comments on a seperate page so I don't know what the problem is. I was wondering the problem is associated with executing two queries on the same page (although I have seen other applications that use a similar approach when using more than one query to access different tables)?
If you have any suggestions they would be appreciated. Thanks, my code is listed below:
$db = new mysqli(myhost, myusername, password, mydatabase);
$query = 'select * from topics';
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<br>';
$blogtext = $row['text'];
$postID = $row['postID'];
?>
<a href="discussionnum.php?postID=<?php echo $postID ?>">
<?php
echo $blogtext;
?>
</a>
<?php
$newresult = mysql_query('select * from shtopics where posts.postID ="'.$newpostID.'"', $db);
$newnum_results = mysql_num_rows($newresult);
if($newnum_results > 0)
{
for ($i=0; $i < $newnum_results; $i++)
{
$row2 = $newresult->fetch_assoc();
echo '<br>';
$newcomment = $row2['comment'];
echo $newcomment;
}
}
else {
echo "No results";
}
}
$result->free();
?>
If you have any suggestions they would be appreciated. Thanks, my code is listed below:
$db = new mysqli(myhost, myusername, password, mydatabase);
$query = 'select * from topics';
$result = $db->query($query);
$num_results = $result->num_rows;
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<br>';
$blogtext = $row['text'];
$postID = $row['postID'];
?>
<a href="discussionnum.php?postID=<?php echo $postID ?>">
<?php
echo $blogtext;
?>
</a>
<?php
$newresult = mysql_query('select * from shtopics where posts.postID ="'.$newpostID.'"', $db);
$newnum_results = mysql_num_rows($newresult);
if($newnum_results > 0)
{
for ($i=0; $i < $newnum_results; $i++)
{
$row2 = $newresult->fetch_assoc();
echo '<br>';
$newcomment = $row2['comment'];
echo $newcomment;
}
}
else {
echo "No results";
}
}
$result->free();
?>