There are methodologies that help in solving this problem, such as Model-View-Controller (MVC). MVC separates your data layer from your logic from presentation layers (UI). A framework such as CodeIgniter will help you in this case. Even if you are not going to use the existing infrastructure, separating your data models from your business logic and then from the user interface objects is relatively easy.
Edit: let's say you have a shopping cart page. You can have a “view” file called cart.php, and then you can send it from other PHP files (“Controllers”), so instead:
<div id = 'special_price'> <?php $result = mysql_query("SELECT price FROM pricelists"); $row = mysql_fetch_assoc($result); echo $row["price"]; ?> </div>
You can do it:
<div id = 'special_price'><?= $price ?></div>
In this case, all the logic and access to the data is processed before you try to display the page.
source share