获取主题PHP中的帖子数量

时间:2010-06-15 20:41:42

标签: php mysql function while-loop

如何显示论坛等主题的帖子数量。我用过这个......(多么苛刻):

function numberofposts($n)
{
    $sql = "SELECT * FROM posts
            WHERE topic_id = '" . $n . "'";

    $result = mysql_query($sql) or die(mysql_error());          
    $count = mysql_num_rows($result);           

    echo number_format($count);
}

列出主题的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
}
?>

虽然这样做的方法很糟糕......我只需知道什么是最好的方法,不要只是指出一个网站,在这里做,因为我正在努力学习许多。好的? :d

感谢。

修改

SQL:

帖子表:

CREATE TABLE `posts` (
  `post_id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `topic_id` mediumint(8) NOT NULL,
  `forum_id` mediumint(8) NOT NULL,
  `user_id` mediumint(8) NOT NULL,
  `post_time` varchar(100) NOT NULL,
  `post_timestamp` mediumint(20) NOT NULL,
  `post_ip` varchar(20) NOT NULL,
  `post_reported` tinyint(1) NOT NULL,
  `post_reportdesc` text NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `posts`
--

INSERT INTO `posts` VALUES(1, 1, 0, 1, '15th Junenee', 0, '', 0, '');

主题表:

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 ;

这可以帮助您了解更多。

4 个答案:

答案 0 :(得分:2)

您可以使用:

"SELECT COUNT(topic_id) FROM posts WHERE topic_id = '?'"

?是一个占位符。如果您使用mysql,则应使用mysql_real_escape_string

$sql = "SELECT COUNT(topic_id)
        WHERE topic_id = '" . mysql_real_escape_string($n) . "'";

如果您使用mysql_fetch_array$row[0]将成为计数。你可以命名,但没有必要。

更好的选择是某种准备好的陈述,例如PDOStatementmysqli_stmt。这有助于防止SQL注入。

答案 1 :(得分:0)

如果您只想要记录数量,则可以使用此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']);
}

答案 2 :(得分:0)

SELECT topic_title, COUNT(*) AS toipic_count
FROM topics
GROUP BY topic_id
ORDER BY topic_id ASC

然后你将不再需要mysql查询,只需使用:

$row['topic_count']

答案 3 :(得分:0)

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

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

没有过多研究你的架构,但你明白了。