1

我有以下 PHP 脚本。我想计算和打印每篇文章的评论。

每篇文章的 id 可以通过以下方式“召回”:(<?php echo $listing['Listing']['listing_id'];?>这将返回 contentid 编号)

现在,我有这个脚本:

<?php
          $db =& JFactory::getDBO();
          $query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ????? ";
          $db->setQuery($query);
          $count = $db->loadResult();
echo ($count); ?>

我试图在 WHERE 子句中添加这个:

"... WHERE contentid = {$listing['Listing']['listing_id']}"

但 $count 返回“0”零。如何在 WHERE 子句中添加此变量?

提前致谢!

4

3 回答 3

2

In the case of an integer:

$query = "SELECT
    COUNT(comments) AS totalcount
WHERE
    contentid = " . ((int) $listing['Listing']['listing_id']);

In the case of a string:

$query = "SELECT
    COUNT(comments) AS totalcount
WHERE
    contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);

The biggest thing to be weary of is SQL injection. This makes your queries safe. The explicit cast to int will ensure an int value is passed, even if the value is erroneous, at least you wont be open to any attack.

于 2012-04-13T18:08:42.953 回答
2

使用 sprintf 并转义字符串。

$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));
于 2012-04-13T18:06:04.517 回答
1

尝试

$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = '".mysql_real_escape_string($listing['Listing']['listing_id'])."'";

或者

$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ".mysql_real_escape_string($listing['Listing']['listing_id']);

取决于数据类型。

于 2012-04-13T18:03:20.973 回答