First of all, I'm not sure I understand what you are using the $total and $i variables for. Your first if statement will run whenever $total is not equal to zero, i.e. for every iteration of the loop except the first. It then resets $i to zero, but it doesn't appear that $i isn't used elsewhere. It seems that you could eliminate these variables and the associated if structure, since that may be producing a problem.
Also, I'd suggesting turning all error reporting on to check for uninitialized vars, etc., that might be causing a problem. At the top of your script, add
<?php
error_reporting(E_ALL);
?>