Wrong: mix HTML and PHP

Do you have such code in your app?

<?php
session_start();
$mysqli = mysqli_connect("localhost", "user", "pwd", "db");

if (mysqli_connect_errno($mysqli)) {
    echo 'MySQL connection error: '.mysqli_connect_error();
    die;
}
?>

<div>
    <h2>Articles</h2>

    <?php
    $result = mysqli_query($mysqli, "
        SELECT a.id, a.title, a.content, u.username
        FROM article a
        JOIN user u ON a.user_id = u.id
    ");
    while($row = mysqli_fetch_assoc($result)): ?>
        <div>
            <h4>
                <a href="article.php?id=<?= $row['id'] ?>"?>
                    <?= $row['title'] ?>
                </a>
            </h4>
            <p>Written by <?= $row['username'] ?></p>
            <div>
                <?= substr($row['content'], 0, 100).'...' ?>
            </div>
        </div>
    <?php endwhile ?>
</div>

Here you’re mixing HTML, PHP and SQL which different things with different purposes.

Never do that anymore.

It’s messy, hard to read, hard to debug, hard to maintain, and won’t land you a job anywhere with such an approach to PHP. In this language it’s easy to make mistakes as it’s easy to “make things work”, but it’s not a reason to do it.

Solution

  • Isolate your code into functions such as init(), getDatabase(), getArticles(), render(), and boot()
  • Put all these functions into a functions.php file
  • Put your HTML into a view.html.php file
  • In your render() function, use ob_start() and ob_get_clean() to render your view into a string and return it
  • Echo your render() function
  • Launch boot() function to launch your app

Even better solution

Procedural code is not modern programming. You should only code with OOP and take advantage of PHP’s ecosystem.

Most projects should use Composer and at least those 4 Symfony components:

More

Read the series You’re not doing it right to step up your PHP game.

Leave a comment