Looking through your code, I'm a bit surprised you get anything useful at all.
You have php that is not surrounded by <?php> and <?>
You while loop is broken by interspersed HTML - so it's broken.
You must remember something very important: php is all executed on the server before the page is sent to the client for rendering by the browser.
If, for example, you wish to have HTML mixed with your php and repeated in a loop, it must be part of the php output.
foreach($row as $r)
Notice how the table may be declared outside the php loop but the rows are generated, in full, within it.