Reputation: 377
I need some help with figuring out the logic for this, because in the most tutorials i saw, they just had to store a topics_count int in the database and every time a topic was created in that specific forum they would increase the topics_count +1 for the forum they were created in;
however can't we achieve this by getting a value using mysqli_num_rows
instead? This would return the total rows (topics) in relation with a forum. But then the problem is how can i create that relation when the forums are inside an array.
Both forums and topics have an:
I am aware of the security problems. This example is just a practice.
This is how i display the forums from the database and echo a href to each forum.
$array_forums = mysqli_fetch_assoc($res_forums);
echo "<div id='forum_{$array_forums["forum_id"]}' class='forum_classic'>";
echo "<div id='forum_classic_status'></div>";
echo "<div id='forum_classic_container'>";
echo "<div id='forum_classic_icon'></div>";
echo "<div id='forum_classic_description'>";
echo "<a href=forum.php?forum=" . urlencode($array_forums["forum_id"]) . ">";
echo "<h1>{$array_forums["forum_title"]}</h1>";
echo "</a>";
echo "<p>{$array_forums["forum_description"]}</p>";
echo "</div>";
echo "</div>";
echo "<div id='forum_classic_topics'>Topics</div>";
echo "<div id='forum_classic_replies'>Replies</div>";
echo "<div id='forum_classic_lastposter'>Lastposter</div>";
echo "</div>";
}
This is how i display the topics in each forum, after a link is clicked.
$forum_id = $_GET['forum'];
//1. Perform database query for topics
$sql_topic = "SELECT * FROM topics WHERE topic_forum_id = {$forum_id}";
$res_topic = mysqli_query($conn, $sql_topic);
//2. Display returned data from topics
if (mysqli_num_rows($res_topic) >= 1) {
$array_topic = mysqli_fetch_assoc($res_topic);
echo "<div id='topic_{$array_topic["topic_id"]}'>{$array_topic["topic_title"]}";
echo "</div>";
} else {
echo "<a href='community.php'>Return To Forum Index</a>";
echo "<p>There are no topics in this forum yet.</p>";
}
Upvotes: 0
Views: 220
Reputation: 377
With the help of @Anil Shrestha , $num will serve as the topic counter.
$sql_topic = "SELECT count(*) FROM topics WHERE topic_forum_id = {$array_forums["forum_id"]}";
$res_topic = mysqli_query($conn, $sql_topic);
$row = mysqli_fetch_row($res_topic);
$num = $row[0];
Upvotes: 1
Reputation: 1200
You can use count to count the number of rows
$sql_topic = "SELECT count(*) FROM topics WHERE topic_forum_id = {$forum_id}";
$row = mysqli_fetch_row($sql_topic);
$num = $row[0];
$num will return the number of topics in specific forum
Upvotes: 1