As predicted, Ive found that there was a small mistake in my code.
In the while statement at the bottom, I closed the bracket AFTER the line that says:
echo $table;
This means that, for each row retrieved in the while function, the table is echoed, which explains why there is a new table for each new row!