> So, what's going wrong here? Why is the PHP that I have added to the template been deleted when I apply the template to a page?
You may be getting caught in the fact that the region above <html> is regarded as an EDITABLE REGION by the template engine. In that case, editable region content is not propagated to child pages.
I have been doing exactly the same thing, but in reverse sortof. My approach is to create the DB pages, then create a NEW child page from the template, and copy/paste content from the existing DB pages into the new child pages. That way I can make sure that all of the important stuff gets into the right place. Of course this presupposes that you know what is the important stuff to copy and where to copy it!
We'd definitely need to see your code for the other two issues.