Your PHP is an absolute mess - the loop code block, for example, is broken to throw in some HTML, php, more html, and then terminating the code block. It's just not done that way.
A php loop must all be in one continious php code block. You need to do a lot of study of php well before the concept of connecting to a database and retrieving data.
Try:
PHP 5 Tutorial[
^]