That's because this line:
echo"<tr><td>";
gets executed on every iteration of the loop, as well as:
echo('</tr>');
.
Either search the board for previously posted code snippets showing how to print data in columns, or re-think your logic in your code. You obviously only want those TR tags outputted before/after the 1st/3rd images.
Also, you need to output the correct amount of cell divisions (TD) for the last row to have the same number of cells as all of the other rows (and a </tr> if one hasn't been outputted yet).