DEV Community

Basim Ghouri
Basim Ghouri

Posted on

How to Create a Notification System in PHP and MySQL

In this tutorial, we will walk through the steps of creating a notification bell using PHP and MySQL. The notification bell will display the number of unread notifications and allow users to mark individual notifications as read or mark all notifications as read with a single click.

// Connect to database
$pdo = new PDO('mysql:host=localhost;dbname=notifications', 'root', '');

Enter fullscreen mode Exit fullscreen mode

Replace "notifications" with the name of your database, and "root" with your database username and password.

Next, we will fetch the notifications from the database and count the number of unread notifications:

// Get notifications
$statement = $pdo->prepare("SELECT * FROM notifications ORDER BY id DESC");
$statement->execute();
$notifications = $statement->fetchAll(PDO::FETCH_ASSOC);

// Count unread notifications
$statement = $pdo->prepare("SELECT COUNT(*) as count FROM notifications WHERE is_read = 0");
$statement->execute();
$unreadCount = $statement->fetch()['count'];

Enter fullscreen mode Exit fullscreen mode

We use the "ORDER BY id DESC" statement to display the most recent notifications first.

Now, let's add the functionality to mark individual notifications as read when clicked:

// Mark notification as read when clicked
if (isset($_GET['notification_id'])) {
    $notificationId = $_GET['notification_id'];
    $statement = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id = :id");
    $statement->bindValue(':id', $notificationId);
    $statement->execute();
    header('Location: ' . $_SERVER['PHP_SELF']);
}

Enter fullscreen mode Exit fullscreen mode

We use the "UPDATE" statement to mark the notification as read, and the "header" function to reload the page after the update is complete.

Next, let's add the functionality to mark all notifications as read with a single click:

// Mark all notifications as read when clicked
if(isset($_GET['clear_notifications'])) {
  $statement = $pdo->prepare("UPDATE notifications SET is_read = 1");
  $statement->execute();
  header('Location: ' . $_SERVER['PHP_SELF']);
  // Hide "No notifications" message from UI
  $notifications = array();
}

Enter fullscreen mode Exit fullscreen mode

We use the same "UPDATE" statement, but without a WHERE clause to update all notifications. We also set the "notifications" array to an empty array to hide the "No notifications" message from the UI.

Finally, let's add the HTML and PHP code to display the notification bell:

<!-- Notification Bell -->
<a href="notifications.php">
    <div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="fa fa-bell"></i>
            <?php if ($unreadCount > 0) : ?>
                <span class="badge badge-danger"><?php echo $unreadCount ?></span>
            <?php else : ?>
                <span class="badge badge-secondary">0</span>
            <?php endif; ?>
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <?php $hasUnreadNotifications = false; ?>
            <?php foreach ($notifications as $notification) : ?>
                <?php if ($notification['is_read'] == 0) $hasUnreadNotifications = true; ?>
                <?php if ($notification['is_read'] == 1) continue; ?>
                <a class="dropdown-item font-weight-bold" href="?notification_id=<?php echo $notification['id'] ?>">
                    <?php echo $notification['message'] ?>
                </a>
            <?php endforeach; ?>
            <?php if (!$hasUnreadNotifications && !isset($_GET['clear_notifications'])) : ?>
                <a class="dropdown-item" href="#">No notifications</a>
            <?php endif; ?>
            <?php if ($hasUnreadNotifications && !isset($_GET['clear_notifications'])) : ?>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="?clear_notifications">Clear all notifications</a>
            <?php endif; ?>
        </div>
    </div>
</a>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)