Php 获取主题中的帖子数

Php 获取主题中的帖子数,php,mysql,function,while-loop,Php,Mysql,Function,While Loop,如何显示论坛等主题的帖子数量。我用这个。。。(多么不切实际): 列出主题的while循环: <?php $sql = "SELECT * FROM topics ORDER BY topic_id ASC LIMIT $start, $limit"; $result = mysql_query($sql) or die(mysql_error()); while($row = mysql_fetch_array($result)) { ?> <div cla

如何显示论坛等主题的帖子数量。我用这个。。。(多么不切实际):

列出主题的while循环:

<?php

$sql = "SELECT * FROM topics ORDER BY topic_id ASC LIMIT $start, $limit";
        $result = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_array($result))
{
?>
<div class="topics">
    <div class="topic-name">
        <p><?php echo $row['topic_title']; ?></p>
    </div>
    <div class="topic-posts">
        <p><?php echo numberofposts($row['topic_id']); ?></p>
    </div>
</div>
<?php
}
?>
主题表:

CREATE TABLE `topics` (
  `topic_id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `section_name` varchar(25) NOT NULL,
  `topic_title` varchar(120) NOT NULL,
  `topic_description` char(120) NOT NULL,
  `user_id` mediumint(8) NOT NULL,
  `topic_time` varchar(100) NOT NULL,
  `topic_views` varchar(1000) NOT NULL,
  `topic_up` mediumint(11) NOT NULL,
  `topic_down` mediumint(11) NOT NULL,
  `topic_status` tinyint(1) NOT NULL,
  PRIMARY KEY (`topic_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
这将有助于您了解更多信息。

您可以使用:

"SELECT COUNT(topic_id) FROM posts WHERE topic_id = '?'"
那个?他是个占位者。如果您使用mysql,您应该使用
mysql\u real\u escape\u string

$sql = "SELECT COUNT(topic_id)
        WHERE topic_id = '" . mysql_real_escape_string($n) . "'";
如果使用
mysql\u fetch\u array
$row[0]
将是计数。你可以说出它的名字,但这不是必须的


更好的选择是某种预先准备好的语句,例如or。这有助于防止SQL注入。

如果只需要记录数,则可以使用此SQL查询:

SELECT COUNT(topic_id) AS 'count' WHERE topic_id = '123'
然后,在你这样做之后:

$result = mysql_query($sql);
if ($result !== false)
{
    $row = mysql_fetch_assoc($result);
    if ($row !== false)
        echo('Number of rows = ' . $row['count']);
}
这样您就不需要任何mysql查询,只需使用:

$row['topic_count']

当您列出主题时,应在联接中包含帖子计数:

SELECT t.*, COUNT(p.post_id) AS post_count
FROM topic t LEFT JOIN posts p ON p.topic = t.topic_id 
GROUP BY t.topic_id

没有过多地研究你的模式,但你明白了重点。

“从主题id=”的帖子中选择COUNT(主题id)作为totalCount?”然后你可以选择行“totalCount”哇,哇,哇,哇,是什么$n?你在原来的帖子中写了代码吗?因为
$n
与你在那里写的是一样的东西(主题id)!你能在我的作品中把它实现到我的代码中吗?谢谢。我不能让它工作。。。你能把它实现到我的代码中吗,我试着把它和你的代码一起放进我的代码中,但它不起作用…告诉我以下内容,这样我就能更了解你的问题:主题id是唯一的?是否要显示文章的标题以及文章在数据库中的位置?那个位置必须是唯一的并且永远不会改变,或者只是为了展示?我已经编辑了OP,添加了数据库表,这样你就可以看到有什么了。你想显示文章的标题和文章在数据库中的位置吗?这个位置必须是唯一的并且永远不会改变,或者只是为了显示?好吧,基本上while循环显示在index.php上,它将列出所有主题,并且在列表中有每行的帖子数。
SELECT topic_title, COUNT(*) AS toipic_count
FROM topics
GROUP BY topic_id
ORDER BY topic_id ASC
$row['topic_count']
SELECT t.*, COUNT(p.post_id) AS post_count
FROM topic t LEFT JOIN posts p ON p.topic = t.topic_id 
GROUP BY t.topic_id