Mixing PHP and HTML

More often than not, beginner PHP developers will create horrendous-looking spaghetti code that is difficult to debug or understand. One of the major reasons behind this is their insistence on mixing the logic of their application with the presentation of their application. As time goes on and more “features” are added, the code base becomes messy, error-prone and impossible to re-use.

A nice example of some spaghetti code in action:


echo '<h1>New Users</h1>';

$sql = "SELECT * FROM users ORDER BY date_registered";
$result = mysql_query($sql) or die(mysql_error());

echo '<table class="my-table-class">';
while($row = mysql_fetch_assoc($result)){
    echo '<tr><td>' . $row['username'] . '</td><td>' . $row['date_registered'] . '</td></tr>';
echo '</table>';

function random_custom_function($var){
    $var = $var + 1;
    return '<span style="font-weight:bold;">' . $var . '</span>';

$sql = "SELECT * FROM table WHERE column = 'test'";
$result = mysql_query($sql) or die(mysql_error());

echo '<div id="test">';
$i = 0;
while($row = mysql_fetch_assoc($result)){
    if($row['type'] == 3){
        echo '<div style="margin-bottom:20px;">' . random_custom_function($row['val']) . '</div>';
        echo '<div style="margin-bottom:20px;">' . $row['val'] . '</div>';

if($i == 0){
    echo '<table>';
    echo '<tr><td>Found none!</td></tr>';
    echo '</table>';

Yuck! Not only is the code above horrible on the eyes, it’s also needlessly complex and error-prone! What if a designer needs to work on the design of the page? What if he or she is not comfortable with PHP?

Do not echo out HTML!

If you plan on taking the “path to recovery”, then this is the first rule that you should take on board. Echo’ing out HTML is horrible and it prevents non-programmers from being able to work with your design! It also prevents your IDE from being able to highlight HTML elements, attributes, ID names and class names!

This means that instead of doing this:

echo '<div id="user_profile">';
echo '<h1>' . $user['name'] . '</h1>';
echo '<img src = "' . $user['profile_picture'] . '" class="profile-pic">';
echo '</div>';

… you should be doing this:

<div id="user_profile">
    <h1><?= $user['name']; ?></h1>
    <img src = "<?= $user['profile_picture']; ?>" class="profile-pic">

To sum up the difference:

  • It’s cleaner looking.
  • You can properly indent your HTML.
  • IDEs will be able to highlight the HTML.
  • It is more designer-friendly, as the distinction between PHP and HTML is much clearer.

Oh, and here’s an example of a loop:

<?php foreach($entries as $entry): ?>
    <h1><?= $entry['title']; ?></h1>
    <p><?= $entry['description']; ?></p>
<?php endforeach; ?>

Do not mix your logic with your presentation!

There are four terms that you need to be aware of:

  • Logic: This refers to the business logic of your application. Examples include database connections, functions, SQL queries, redirects, session handling and other pieces of logic that control the flow of your application.
  • Presentation: This refers to the appearance / client-side of your application. We’re talking about HTML, CSS and in some cases, JavaScript.
  • Presentation Logic: This is the type of logic that determines the appearance of a certain piece of data. For example, if you are outputting a list of registered users, you might want to highlight disabled accounts in red. This type of logic does not control the flow of your application and it plays no part in any of the business logic! It’s only purpose is to control the layout and appearance of your application!
  • Separation of concerns: Simply put, “Separation of concerns” is a design principle that splits an application up into its relevant “categories (concerns).” Example: Code that handles database connections and SQL queries will be kept separate from the part of the application that handles requests and redirects. In this particular case, we’ll keep it simple by saying that we’re talking about the act of keeping our logic separated from our presentation!


Why should you separate them?

  1. Generally speaking, file sizes become smaller. Nobody wants to open 4000 lines of logic mixed with HTML.
  2. You don’t have to worry too much about designers damaging the internal workings of your application. They can add design features without having to look at the business logic.
  3. It is much cleaner and easier on the eyes.
  4. Bugs are easier to hunt down.
  5. Your business logic will become easier to modify (adding new features, etc).
  6. Re-designs are much less of a hassle.
  7. It is easier to find certain parts of the application if know where everything is.

An example of the “separation of concerns” principle that you might already be using?

HTML and external CSS stylesheets!

In this particular scenario, HTML defines the structure, whereas CSS defines the appearance of said structure. Whenever you need to change a colour or add a border, you can open the CSS file and make your changes. i.e. You don’t need to edit the HTML at all. It’s a completely separate matter!


MVC (Model–View–Controller) frameworks are popular because they help to enforce the separations of concerns principle (they also come with a lot of useful libraries and helper classes). Generally speaking, an MVC framework will split your application up into three separate parts:

  • Model: The Model represents the data. Examples: A MySQL table or an XML file.
  • View: The View displays data (presentation). In most cases, view files will consist of HTML and some basic presentation logic.
  • Controller: The Controller passes data to the view. It receives form data from the view and it controls the flow of your application (redirects, etc).

If you are interested in using a PHP MVC framework, then you should check out some of the following:

Template Engines

Another alternative is to use a template engine such as Twig, which will allow you to separate your logic from your appearance. In a lot of cases, these templating engines are actually used inside some of the MVC frameworks that were listed above! A cool thing about Twig is that is actually supports view inheritance!

Failing That…

If you don’t have the time to learn about using an MVC framework or a templating engine, then you should at least make a huge effort to organize your application into its relevant parts / folders! Examples:

  • Separate your HTML from your business logic.
  • Keep your database connection code in one place. Use the require statement to include it in your scripts.
  • Learn about object-orientated programming.
  • Try to keep your SQL queries separated from the parts of your application that handle requests, redirects and form data.
  • Do NOT echo out HTML with PHP.
  • Keep your folders organised…
  • … and most of all – BE CONSISTENT!