Coding Examples

PHP & MySQL News Feed

This example from my HTML & CSS assessment uses PHP with PDO to retrieve news articles from a MySQL database and render them dynamically. It also escapes output to protect the page from unsafe content.

<?php
require_once __DIR__ . '/database.php';

$stmt = $pdo->query("
    SELECT id, type, image, title, description, button, author_image, author, date
    FROM news
");

$newsItems = $stmt->fetchAll();
?>

<div class="news-grid">
    <?php foreach ($newsItems as $item): ?>
        <?php $isCareer = $item['type'] === 'Careers'; ?>

        <a href="#" class="news-card <?= $isCareer ? 'news-card__career' : '' ?>">
            <div class="news-card__media">
                <img
                    src="<?= htmlspecialchars('img/' . $item['image']) ?>"
                    alt="<?= htmlspecialchars($item['title']) ?>"
                >

                <span class="news-card__tag <?= $isCareer ? 'news-card__tag--career' : '' ?>">
                    <?= htmlspecialchars($item['type']) ?>
                </span>
            </div>

            <div class="news-card__content">
                <h2><?= htmlspecialchars($item['title']) ?></h2>

                <p><?= htmlspecialchars($item['description']) ?></p>

                <div class="news-card__meta">
                    <img
                        class="news-card__avatar"
                        src="<?= htmlspecialchars('img/' . $item['author_image']) ?>"
                        alt="<?= htmlspecialchars($item['author']) ?>"
                    >

                    <div>
                        <strong>Posted by <?= htmlspecialchars($item['author']) ?></strong>
                        <span>
                            <?= date('jS F Y', strtotime($item['date'])) ?>
                        </span>
                    </div>
                </div>
            </div>
        </a>
    <?php endforeach; ?>
</div>