WHERE子句中的PHP变量,如何?

时间:2012-04-13 18:00:27

标签: php mysql variables where-clause

我有以下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子句中添加此变量?

提前致谢!

3 个答案:

答案 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']);

取决于数据类型。