Quick glance of your code and I saw that your table structure was a little bit weird. Remember a tr-element means a new row and a td-element means a new column within that row. You create a tr-element outside the loop and then you do it inside, this is usually alarming since it's unlikely the table structure gets correct at the end. If you need a row outside your loop, then make sure you finish it before you start iterating.
You include alot of unseen html, but I assume you know there isn't any divs and table-structure in those since you ask us to find the error.