in reply to foreach loop

Don't mix HTML with actual programming. Make a subroutine that builds the data fetched from the database into an array. Then have another subroutine that builds the HTML from that array. Better yet, use HTML::Template. I'm not entirely sure what your code's problem is, but I suspect decupling your data from code will magically make it go away.