What is by far the most important concept to keep in mind while writing PHP code, or for that matter any web-based code, is to separate the code from the content. By separating the code from the content, you place as much of the PHP, MySQL, and other queries at the top of the page as possible and then follow it with whatever HTML output you desire. A sample of what this might look like is considered below. In addition, comment your code so that you and others know what is going on inside the code. Adding a concise, informative blurb at the beginning of each code block can make a world of difference.
As the example shows, there is no PHP code in the lower half of the page. However, this is not very realistic for actual web pages. You will pretty much always have some variable to look up, table entry to query, etc which will prevent you from completely separating your code. The idea, though, is that we get as much of the PHP out of the way at the begining of the file, and only make minor calls later on. In the HTML part you should only need to output statements (echo/print) and control statements (if/for/while etc). Use of echo statements to output the main HTML should be avoided at all times. Also, NO SQL statements should appear in the lower part of the script. Also notice that the comments are kept to a minimum and tell us exactly what the next small chunk of code will do.