WHERE 子句中的 PHP 变量,如何


PHP variables in WHERE clause, how to?

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

提前感谢!

如果是整数:

$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 值,即使该值是错误的,至少您不会受到任何攻击。

使用 sprintf 并转义字符串。

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

试试

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

取决于数据类型。