我想创建一个基于sql查询结果的计数器。 sql查询获取一堆数据,然后逐行计算持续天数,然后根据总天数计算当天有多少结果。 我一直试图弄清楚为什么我的计数器没有保留任何值。我知道SQL结果正在拉动数据。有任何想法吗?php - 虽然计数器不工作
这个想法是查看开始日期和当前日期之间的天数是否大于365天,然后启动一个计数器,如果它少于365天,则启动一个不同的计数器。
$anymatches=mysql_num_rows($result_id);
if ($anymatches > 0)
{
while($row = mysql_fetch_array($result_id))
{
/*** Performing a calculation to get the number of days ***/
$calctoday = date("Y-m-d"); // trying to capture current date
$sd = start_check_gap($row[1],45); // getting a date from the sql query
$dateDiff = strtotime($calctoday) - strtotime($sd); // probably a better way to do this but calculating the difference between start date and current date.
$totaldays = floor($dateDiff/(60*60*24));
$data = $dateDiff/86400;
$data = number_format($data, 0, '.', '');
if ($data > 365)
{
$pernumc1 = 0;
while($data > 365)
{
$pernum1 = $pernumc1;
$pernumc1++;
}
}
elseif ($data < 365)
{
$pernumc2 = 0;
while($data < 365)
{
$pernum2 = $pernumc2;
$pernumc2++;
}
}
else
{
$pernumc3 = 0;
while($data != FALSE)
{
$pernum3 = $pernumc3;
$pernumc3++;
}
}
谢谢大家以下的意见是我的工作。我想发布我的正确版本,因为任何人都有相同类型的问题。我能够根据你的无限循环评论找出问题的根源,以及两个问题。第一个问题是我的sql查询中有一个错误。一旦我纠正错误,然后我注意到你们提到的无限循环问题。基本上下面是我做的。我删除了每个if()中的while,并将开始计数器变量$ pernumc1移动到第一个之上,并且它像魅力一样工作。看起来我仍然需要清理日期比较,但它总体上工作。
$anymatches=mysql_num_rows($result_id);
if ($anymatches > 0)
{
$pernumc1 = 0;
$pernumc2 = 0;
$pernumc3 = 0;
while($row = mysql_fetch_array($result_id))
{
$calctoday = date("Y-m-d");
$sd = start_check_gap($row[1],45);
$dateDiff = strtotime($calctoday) - strtotime($sd);
$totaldays = floor($dateDiff/(60*60*24));
$data = $dateDiff/86400;
$data = number_format($data, 0, '.', '');
if ($data > 548)
{
$pernum1 = $pernumc1;
$pernumc1++;
}
elseif ($data > 365)
{
$pernum2 = $pernumc2;
$pernumc2++;
}
elseif ($data < 365)
{
$pernum3 = $pernumc3;
$pernumc3++;
}
}
[**请不要在新代码中使用'mysql_ *'函数**](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。 – Kermit 2013-02-25 16:46:21
'$ calctoday'是完全不必要的 - 您将当前日期转换为格式化的字符串,然后将其直接转换回时间戳进行比较。你可以使用'time()'函数,并保存你的程序一大堆工作。或者更好的是,使用'DateTime'类和['DateTime :: diff()'](http://php.net/manual/en/datetime.diff.php)函数;它比'strtotime()'强大得多。 – SDC 2013-02-25 16:46:57
这似乎也可以通过SQL查询本身轻松完成。 – 2013-02-25 16:58:52