当我将季节结束日期作为变量传递给此函数时,我收到此错误:警告:除零
function win_percentage($season_start, $season_end)
{
$wins = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Won' AND gamedate >= $season_start AND gamedate <= $season_end;");
$losses = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Lost' AND gamedate >= $season_start AND gamedate <= $season_end;");
$winstotal = mysql_fetch_array($wins);
$lossestotal = mysql_fetch_array($losses);
$resultgames = $winstotal['COUNT(result)'] + $lossestotal['COUNT(result)'];
$winratio = ROUND(($winstotal['COUNT(result)'] / $resultgames),2) * 100;
return $winratio;
}
echo win_percentage('2012-01-01', '2012-09-10')
输出:警告:除以零
但是,当我将季节结束的日期值直接放在函数中时,它可以完美地运行。这些代码块之间的唯一区别是第3行和第4行的结束,其他一切都是相同的。为什么我不能在没有抛出错误的情况下将season_end传递给这个函数?
function win_percentage($season_start, $season_end)
{
$wins = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Won' AND gamedate >= $season_start AND gamedate <= '2012-12-31';");
$losses = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Lost' AND gamedate >= $season_start AND gamedate <= '2012-12-31';");
$winstotal = mysql_fetch_array($wins);
$lossestotal = mysql_fetch_array($losses);
$resultgames = $winstotal['COUNT(result)'] + $lossestotal['COUNT(result)'];
$winratio = ROUND(($winstotal['COUNT(result)'] / $resultgames),2) * 100;
return $winratio;
}
echo win_percentage('2012-01-01', '2012-09-10')
输出:57%
提前致谢!
答案 0 :(得分:0)
您需要将日期放在引号中:
$wins = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Won' AND gamedate >= $season_start AND gamedate <= '$season_end';");
$losses = mysql_query("SELECT COUNT(result) FROM scorecards WHERE result = 'Lost' AND gamedate >= $season_start AND gamedate <= '$season_end';");
如果您开始使用mysqli或PDO并使用它们的绑定参数,这种事情会容易得多 - 它会为您处理所有引用,以及避免SQL注入。
答案 1 :(得分:0)
在查询中使用{/ 1}}时,您应该在日期值之前和之后加上'
:AND gamedate >= '$season_start' AND gamedate <= '$season_end'
您还应该使用mysqli
。
您还应避免将日期保留为数据库中的字符串。