使用where时,COUNT查询返回null

时间:2017-06-18 15:17:58

标签: php mysql wordpress mysqli

我正在构建一个在WordPress网站上运行的小型PHP脚本。

我想查询我的表中有多少项目有特定的电子邮件。出于某种原因,它在不使用where语句时有效,但是一旦我添加WHERE email=test42@foo.com,它就会返回null。我不明白为什么。

<?php
  require('../wp-config.php');
  $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
  $email = $_GET['email'];
  global $wpdb;

  // This works
  $countQuery = "SELECT COUNT(*) as count FROM `".$wpdb->prefix."mytable`";

  // Once I add a filter, it returns null
  $countQuery = $countQuery." WHERE `email`=`test42@foo.com`";

  $rs = mysql_query($countQuery);
  $result = mysql_fetch_array($rs);

  // Later, I'd like to access $result['count']
  // but the $result itself is NULL
  var_dump("result", $result);
?>

我尝试添加以下行以查看是否有任何错误,但未显示其他输出:

ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_reporting(E_ALL);
ini_set('display_errors', 'on');

如何解决这个问题?为什么会出现这种情况?我不确定它是否与WordPress有任何关系,但由于只是通过添加WHERE email=test42@foo.com来破坏功能,我的想法已经不多了。

1 个答案:

答案 0 :(得分:2)

评论太长了。

您的查询有错误:

SELECT COUNT(*) as count
FROM mytable  -- simplified for illustration
WHERE `email` = `test42@foo.com`

如果您只是针对数据库运行此查询,则会说test42@foo.com之类的内容不是有效列或类似内容。

因此,第一条建议是测试您的查询。

其次,如果您参数化您的查询 - 这是正确的事情 - 那么您将永远不会遇到此问题。带参数值的Munging查询可能导致难以解决语法问题(以及SQL注入漏洞)。