打印出COUNT - SQL / PHP

时间:2011-08-17 19:36:37

标签: php sql printing count

我有这段代码:

$topics= mysql_query("SELECT COUNT(*) FROM forum_topics WHERE forum_id=".$h['forum_id'].""); 
                print $topics; //This prints out 1, but should be 14?

如您所见,我从表中选择COUNT。该表包含14行。我怎么打印出来?就像现在一样,当我打印出$主题时,它只是说资源ID#18。

5 个答案:

答案 0 :(得分:2)

你需要这样做:

$topics = mysql_query("SELECT COUNT(*) FROM forum_topics WHERE forum_id=".$h['forum_id'].""); 
$result = mysql_fetch_assoc($topics);
print $result['COUNT(*)'];

答案 1 :(得分:1)

然后你需要像

这样的东西
if ($row = mysql_fetch_row($topics))
{
   echo $row[0];
}

答案 2 :(得分:1)

$topics= mysql_query("SELECT COUNT(*) as Count FROM forum_topics WHERE forum_id=".$h['forum_id']."");

$topics将无法打印14。该查询返回Resource ID上的successfalse上的error

来源:Link

如果你想获得你可以做的伯爵,

$rows = mysql_fetch_array($topics) //You can use this since it's only one record
{
     echo $rows['Count'];
}

如果必须获得多条记录,可以使用

while($rows = mysql_fetch_array($topics))
{
     echo $rows['Count']."</br>";
}

答案 3 :(得分:0)

$topics= mysql_query("SELECT COUNT(*) as count FROM forum_topics WHERE forum_id=".$h['forum_id'].""); 
while($row = mysql_fetch_array($topics)){
    echo $row['count'];
}

答案 4 :(得分:0)

这是因为$ topics是资源,而不是结果集。您需要使用mysql_fetch_assoc,mysql_fetch_array获取结果集(数组),或者在这种情况下您可以使用mysql_fetch_row。

http://us.php.net/manual/en/ref.mysql.php