In modern social apps and websites, real-time chat has become an essential feature. When developing this functionality, an important feature is being able to mark messages as read or unread, so users can easily see which messages have been read. This article will guide you through how to implement this in PHP using MySQL.
To implement the message read and unread status functionality, we need to create two tables in the database: one for users and another for messages.
CREATE TABLE users ( id INT(11) AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL );
CREATE TABLE messages ( id INT(11) AUTO_INCREMENT PRIMARY KEY, sender_id INT(11) NOT NULL, receiver_id INT(11) NOT NULL, message TEXT, is_read TINYINT(1) DEFAULT 0 );
In the database design above, the `users` table stores user ID and username, while the `messages` table contains message ID, sender ID, receiver ID, message content, and the read status.
Next, we will look at some example code to demonstrate how to handle the read and unread status of messages.
<?php // Connect to the database $connection = mysqli_connect('localhost', 'username', 'password', 'database_name'); // Fetch the list of users $query = mysqli_query($connection, "SELECT * FROM users"); $users = mysqli_fetch_all($query, MYSQLI_ASSOC);
<?php // Fetch the current user ID $user_id = $_SESSION['user_id']; // Fetch unread messages $query = mysqli_query($connection, "SELECT * FROM messages WHERE receiver_id = '$user_id' AND is_read = 0"); $unread_messages = mysqli_fetch_all($query, MYSQLI_ASSOC); // Mark unread messages as read foreach ($unread_messages as $message) { $message_id = $message['id']; mysqli_query($connection, "UPDATE messages SET is_read = 1 WHERE id = '$message_id'"); } // Fetch read messages $query = mysqli_query($connection, "SELECT * FROM messages WHERE receiver_id = '$user_id' AND is_read = 1"); $read_messages = mysqli_fetch_all($query, MYSQLI_ASSOC);
<?php // Display unread messages foreach ($unread_messages as $message) { echo "<div class='unread-message'>{$message['message']}</div>"; } // Display read messages foreach ($read_messages as $message) { echo "<div class='read-message'>{$message['message']}</div>"; }
In the code above, we first connect to the database and fetch all unread messages for the current user. We then update these unread messages to mark them as read, and finally display both the unread and read messages.
In this tutorial, we successfully implemented message read and unread status flags for PHP real-time chat. As your requirements evolve, you can enhance this functionality further, such as by adding message notifications or delivery receipts.
This concludes the tutorial on PHP development of message read and unread status flags for real-time chat functionality. We hope it helps with your development work!