You can't do this strictly in PHP, but you can use a javascript function, on a loop, to run an AJAX request to a PHP file, every 5 seconds or so, to see if the logged in user has received any notifications recently. Which the PHP files responds with a json array with the notification details for the ajax request to enter into the DOM.
For my example, I'll be using jQuery in my script to run ajax.
HTML file (index.php)
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var userid = "<?php echo $_SESSION['id']; ?>";
setInterval(NotificationRequest, 5000); //will run the function 'NotificationRequest' every 5 seconds
function NotificationRequest() {
$.ajax({
url: 'checknoti.php', //the php file to request
dataType: 'text',
data: {data : userid},
method: 'POST',
success: function(result) {
$('div#notification').html(result); //insert result from file to inside the div element
}
});
}
</script>
</head>
<body>
<h1>Notification List</h1>
<div id="notification"></div>
</body>
</html>
PHP file (checknoti.php)
$conn = mysqli_connect("127.0.0.1", "username", "password", "database");
$userID = $_POST['data'];
$sql = "SELECT * FROM `notification` WHERE `ID_USER`='$userID' AND `VIEWED`='0'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_accoc($result);
echo $row['title'];
This script (not exactly), should result in the ajax request asking the server for a notification that hasn't been viewed by the user yet, then the html will will update the text inside the DIV (with id "notification"), with the echod notification title.
More on included methods:
- https://www.w3schools.com/jsref/met_win_setinterval.asp
- http://api.jquery.com/html/
- http://api.jquery.com/jQuery.Ajax/