我有以下PHP脚本。我想计算并打印每篇文章的评论。
每篇文章的ID都可以被“召回”:<?php echo $listing['Listing']['listing_id'];?>
(这会返回有争议的数字)
现在,我有这个脚本:
<?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子句中添加此变量?
提前致谢!
答案 0 :(得分:2)
使用sprintf并转义字符串。
$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));
答案 1 :(得分:2)
在整数的情况下:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . ((int) $listing['Listing']['listing_id']);
如果是字符串:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);
最令人厌烦的是SQL注入。这使您的查询安全。显式转换为int
将确保传递int值,即使该值是错误的,至少您不会对任何攻击开放。
答案 2 :(得分: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']);
取决于数据类型。