PHP函数返回ZERO

时间:2010-03-30 22:08:49

标签: php mysql

我在使用这个PHP函数时遇到了麻烦。它一直返回零,但我知道SQL语句有效,因为我自己查询过它。我有什么想法我做错了吗?最后一行对我没有意义......我正在编辑其他人写的代码。假设日期为3月,此函数应返回数百个数字。谢谢!

    function getCountBetweenDays($day1,$day2,$service)

{

    global $conn;

    if ($service==1){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}



    elseif($service==2){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}



        elseif($service==3){

$query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";}

$result = mysql_query($query,$conn);

  $num = mysql_fetch_array ($result);

  return $num['NUM'];

}

6 个答案:

答案 0 :(得分:3)

在您的函数中尝试一些调试输出,例如

function getCountBetweenDays($day1,$day2,$service)
{
  global $conn;

  switch($service) {
    case 1:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    case 2:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    case 3:
      $query = "SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'";
      break;
    default:
      die('unknown value for $service');
  }

  echo '<pre>Debug: $query=', htmlspecialchars($query), '</pre>';
  $result = mysql_query($query,$conn) or die('mysql_query failed: '.htmlspecialchars(mysql_error($conn)));
  echo '<pre>Debug: numrows=', mysql_num_rows($result), '</pre>';
  $num = mysql_fetch_array($result);

  return $num['NUM'];
}

答案 1 :(得分:1)

首先,添加

if (!$result) echo mysql_error(); 
每次mysql_query()调用后

查看是否有任何错误。我很确定有。

答案 2 :(得分:1)

您的查询不是格式化的,它们是:

"SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59';";

他们应该是:

"SELECT COUNT(*) as NUM FROM `items` WHERE `modified` BETWEEN '$day1 00:00:00' AND '$day2 23:59:59'"; 

每个查询都有一个额外的分号。并使用or die mysql_error()打印出错误。

这一部分:

$num = mysql_fetch_array ($result);

  return $num['NUM'];

我已替换为:

$num = mysql_fetch_array ($result);

extract($num);

  return $NUM;//if this is your field name

答案 3 :(得分:1)

修正了......愚蠢的错误。抱歉,我对PHP和MySQL很陌生。

getCountBetweenDays(2010-3-1,2010-3-28,CONT_ALL_SERVICE);

应该是:

getTweetCountBetweenDays('2010-3-1','2010-3-28',CONT_ALL_SERVICE);

感谢大家的帮助,我现在知道如何正确调试!

答案 4 :(得分:0)

您正在尝试使用关联索引['s']引用数字索引[n]。将此内容指定给您的查询

mysql_fetch_array($result, MYSQL_BOTH)

或者只是做

mysql_fetch_assoc($result);

这将允许您通过关联引用索引

答案 5 :(得分:-1)

  

返回$ num ['NUM'];

表示返回数组的'num'部分;将“NUM”更改为1或2,然后尝试