if it doesn't seem to end loading, how far does it get? Use "View source" in your browser to find out. This should at least indicate which of the php sections is causing the problem.
The final "exit" is likely to be a problem, as that may kill the interpreter before displaying the last two lines of the html. I ahven't used it like this, so I can't say for certain. In any case, I'm guessing that that was just added in desperation, in an attempt to fix the not loading problem.
It's hard to say for certain, with the indentation of your code, but you seem to be missing a lot of closing brackets there. Are you sure the script runs without errors, or do you just have error display disabled?