My mistake, I should have checked your logic but I didnt.
You wanted 3 columns.
So we have to modify the $i looping a bit.
Instead of
if ($i % 3 == 0)
echo "</tr>";
$i++;
We should use:
if ($i % 3 == 2)
echo "</tr>";
$i++;
This comes up with another problem: what if the number of records is not a multiple of 3?
There are various ways to solve this, but it depends on what you want.