运行MySQL查询时出错

时间:2012-05-03 02:03:43

标签: php mysql

当我尝试使用下面的代码时,我收到错误Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given

include('config.php');

$con = mysql_connect($dbhost,$dbuser,$dbpasswd);
if (!$con)
  {
      die('Could not connect: ' . mysql_error());
  } else {
      mysql_select_db($dbname, $con);
  }
$date = getdate();
$result = mysql_query("SELECT * FROM '" . $table_prefix . "users' where user_regdate = '" . $date . "'");
$total = 0;
while($row = mysql_fetch_array($result))
  {
  $total++;
  echo $row['username'];
  echo "<br />";
  }

3 个答案:

答案 0 :(得分:1)

您已使用单引号'引用了您的表名。如果引用它,请使用反引号。单引号仅适用于MySQL中的字符串文字。这会导致查询中出现语法错误。

$result = mysql_query("SELECT * FROM `" . $table_prefix . "users` where user_regdate = '" . $date . "'");

接下来,PHP中的getdate()返回一个数组而不是日期字符串,当作为字符串传递给查询时,它会为您的查询提供单词Array。相反,使用MySQL的本机日期函数以MySQL期望的格式获取今天的日期(yyyy-mm-dd):

在评论后修改

由于你有一个unix时间戳而不是一个日期列,所以创建一个日期的Unix时间戳:

where user_regdate = UNIX_TIMESTAMP(GETDATE())

mysql_query()调用进行一点错误检查会显示查询中的错误来源,并且确实有必要防止您的脚本导致致命错误。

$result = mysql_query("SELECT * FROM `" . $table_prefix . "users` where user_regdate = '" . $date . "'");
if (!$result) {
  // query failed
  echo mysql_error();
}
else {
   // all is well, proceed with fetch...
}

最后,我注意到您正在将行数收集到$total++中。这是不必要的(除非您执行一些我们未看到的更具体的逻辑),因为该值可通过mysql_num_rows($result)获得。

答案 1 :(得分:0)

您的查询错误。来自http://php.net/manual/en/function.mysql-query.php

  

mysql_query在成功时返回资源,在出错时返回false。

答案 2 :(得分:0)

因为它返回0行检查mysql_num_rows()     包括( '的config.php');

$con = mysql_connect($dbhost,$dbuser,$dbpasswd);
if (!$con)
  {
      die('Could not connect: ' . mysql_error());
  } else {
      mysql_select_db($dbname, $con);
  }
$date = getdate();
$result = mysql_query("SELECT * FROM '" . $table_prefix . "users' where user_regdate = '" . $date . "'");
$total = 0;
if(mysql_num_rows($result)){
while($row = mysql_fetch_array($result))
  {
  $total++;
  echo $row['username'];
  echo "<br />";
  }
}