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

标签 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 子句中添加此变量?

提前致谢!

最佳答案

在整数的情况下:

$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注入(inject)。这使您的查询安全。显式转换为 int 将确保传递一个 int 值,即使该值是错误的,至少您不会受到任何攻击。

关于WHERE 子句中的 PHP 变量,如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145913/

相关文章:

mysql - 将数据框中的一行数据直接插入到 R 中的数据库中

swift - 如何将图像作为变量传递给单独的 View Controller 中的 UIImageView?

c - 如何在变量中获取curl输出?

php - 是否可以使用 PHP 检测 css 伪元素?

php - Laravel phpunit 总是 404

php - Laravel TokenMismatchExceptionVerifyCsrfToken.php :67 find route

php - mcrypt_encrypt 在包含 ":"(冒号)的字符串上

php - MySQL选择复杂子查询作为字段

mysql - SQL Server 到 MySQL 数据传输

mysql - 如何在 Hibernate 中使用 Mysql 变量?