The basic idea is that if you are counting from $i = 1, then when $i divided by 3 leaves a remainder of 1, you need to begin a new row. When $i is perfectly divisible by 3, you need to end the current row.
Of course, after looping through the records you should check if $i is divisible by 3 one more time. If it is not, insert the required number of blank cells, then end the row.
Now, read the PHP manual on the Arithmetic Operators.