When I pass the season end date as a variable to this function I get this error: Warning: Division by zero
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')
OUTPUT: Warning: Division by zero
However, when I put a date value for the season end directly in the function it works perfectly. The only difference between these to blocks of code is the end of lines 3 and 4, everything else is identical. Why can’t I pass season_end to this function without the error being thrown?
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')
OUTPUT: 57%
Thanks in advance!
You should put
'before and after your date values when you use them in a query:AND gamedate >= '$season_start' AND gamedate <= '$season_end'You should also use
mysqli.You should also avoid keeping dates as strings in your database.