Skip to main content

Build Push Notification System with PHP & MySQL

In our previous tutorial, we have explained how to develop School Management System with PHP & MySQL. In this tutorial, we will explain how to Build Push Notification System with PHP & MySQL.

Push Notification is the most used communication channel by web applications to stay in contact with their users. When we visit any website, we see a notification consent alert to allow or block notification. These alerts are created by websites to get consent to display notifications with latest updates, news etc. If we grant permissions to notification display then the notifications are pushed by website administrator to display to website users.

Currently, the push notification is the most demanding functionality that’s implemented in websites. So if you’re developing web application and need to implement push notification functionality then you’re here at right place. In our previous tutorial you learned how to implement product search filtering with PHP, In this tutorial you will learn how to create Push Notification System with PHP and MySQL.


Also, read:

We will cover this tutorial step by step with live example to create notifications with push details by administrator and normal can login to see the push notifications.

So let’s implement Push notification System with PHP and MySQL. The major files are:

  • login.php
  • index.php
  • manage.php
  • notification.js
  • notification.php
  • User.php: Class to hold user methods.
  • Notification.php: Class to hold notification methods.

Step1: Create MySQL Database Table

First we will create MySQL database table notification_user to admin and normal user for testing the push notification system.

CREATE TABLE `notification_user` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `notification_user`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `notification_user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

We will insert few user records for testing purpose.

INSERT INTO `notification_user` (`id`, `username`, `password`) VALUES
(1, 'webdamn', '12345'),
(2, 'admin', '12345');

We will create MySQL database table notifications to store notifications details.

CREATE TABLE `notifications` (
  `id` int(11) NOT NULL,
  `title` varchar(250) NOT NULL,
  `message` text NOT NULL,
  `ntime` datetime DEFAULT NULL,
  `repeat` int(11) DEFAULT 1,
  `nloop` int(11) NOT NULL DEFAULT 1,
  `publish_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `username` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `notifications`
  ADD PRIMARY KEY (`id`);
  
ALTER TABLE `notifications`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Step2: Design User Login Form

We will create login.php file and design login form.

<div class="container">		
	<h2>User Login:</h2>
	<div class="row">
		<div class="col-sm-4">
			<form method="post">
				<div class="form-group">
				<?php if ($message ) { ?>
					<div class="alert alert-warning"><?php echo $message; ?></div>
				<?php } ?>
				</div>
				<div class="form-group">
					<label for="username">Username:</label>
					<input type="username" class="form-control" name="username" required>
				</div>
				<div class="form-group">
					<label for="password">Password:</label>
					<input type="password" class="form-control" name="password" required>
				</div>  
				<button type="submit" name="login" class="btn btn-default">Login</button>
			</form><br>					
		</div>
	</div>
</div>	

We will handle user login functionality by calling login() method from User.php class. We will store username into session to use while implementing push notification functionality.

session_start();
$message = '';
if (!empty($_POST['username']) && !empty($_POST['password'])) {
	
	include_once 'config/Database.php';
	include_once 'class/User.php';

	$database = new Database();
	$db = $database->getConnection();
	$user = new User($db);

	$user->username = $_POST['username'];
    $user->password = $_POST['password'];	
	
	if($user->login()) {
		$_SESSION['username'] = $user->username;
		header("Location:index.php");
	} else {
		$message = "Invalid username or password!";
	}
}

We will implement method login in class User.php.

function login (){		
	$stmt = $this->conn->prepare("
		SELECT id as userid, username, password 
		FROM ".$this->userTable." 
		WHERE username = ? AND password = ? ");
	$stmt->bind_param("ss", $this->username, $this->password);	
	$stmt->execute();
	$result = $stmt->get_result();		
	return $result;			
}

Step3: Display User Account

We will create index.php file to display logged in user details. We will also display manage notification section for Administrator user.

<div class="container">		
	<h2>Example: Build Push Notification System with PHP & MySQL</h2>	
	<h3>User Account </h3>
	<?php if(isset($_SESSION['username']) && $_SESSION['username'] == 'admin') { ?>
		<a href="manage.php">Manage Notification</a> | 
	<?php } ?>
	<?php if(isset($_SESSION['username']) && $_SESSION['username']) { ?>
		Logged in : <strong><?php echo $_SESSION['username']; ?></strong> | <a href="logout.php">Logout</a>
	<?php } else { ?>
		<a href="login.php">Login</a>
	<?php } ?>
	<hr> 
	<?php if (isset($_SESSION['username']) && $_SESSION['username']) { ?>
		<div <?php if($_SESSION['username'] != 'admin') { ?> id="loggedIn" <?php } ?>>
			<h4>
				You're welcome! You can manage 
			</h4>
		</div>
	<?php } ?>		
</div>	

Step4: Manage Notifications and list

We will create file manage.php and manage Administrator functionality to create new notification with details and assign to users to display push notifications. We will call method saveNotification() from class Notification.php. We will also list created notifications on this page.

<div class="row">
	<div class="col-sm-6">
		<h3>Add New Notification:</h3>
		<form method="post"  action="<?php echo $_SERVER['PHP_SELF']; ?>">										
			<table class="table borderless">
				<tr>
					<td>Title</td>
					<td><input type="text" name="title" class="form-control" required></td>
				</tr>	
				<tr>
					<td>Message</td>
					<td><textarea name="message" cols="50" rows="4" class="form-control" required></textarea></td>
				</tr>			
				<tr>
					<td>Broadcast time</td>
					<td><select name="ntime" class="form-control"><option>Now</option></select> </td>
				</tr>
				<tr>
					<td>Loop (time)</td>
					<td><select name="loops" class="form-control">
					<?php 
						for ($i=1; $i<=5 ; $i++) { ?>
							<option value="<?php echo $i ?>"><?php echo $i ?></option>
					<?php } ?>
					</select></td>
				</tr>
				<tr>
					<td>Loop Every (Minute)</td>
					<td><select name="loop_every" class="form-control">
					<?php 
					for ($i=1; $i<=60 ; $i++) { ?>
						<option value="<?php echo $i ?>"><?php echo $i ?></option>
					<?php } ?>
					</select> </td>
				</tr>
				<tr>
					<td>For</td>
					<td><select name="user" class="form-control">
					<?php 		
					$allUser = $user->listAll(); 							
					while ($user = $allUser->fetch_assoc()) { 	
					?>
					<option value="<?php echo $user['username'] ?>"><?php echo $user['username'] ?></option>
					<?php } ?>
					</select></td>
				</tr>
				<tr>
					<td colspan=1></td>
					<td colspan=1></td>
				</tr>					
				<tr>
					<td colspan=1></td>
					<td><button name="submit" type="submit" class="btn btn-info">Add Message</button></td>
				</tr>
			</table>
		</form>
	</div>
</div>
<?php 
if (isset($_POST['submit'])) { 
	if(isset($_POST['message']) and isset($_POST['ntime']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['user'])) {
		$notification->title = $_POST['title'];
		$notification->message = $_POST['message'];
		$notification->ntime = date('Y-m-d H:i:s'); 
		$notification->repeat = $_POST['loops']; 
		$notification->nloop = $_POST['loop_every']; 
		$notification->username = $_POST['user'];	
		if($notification->saveNotification()) {
			echo '* save new notification success';
		} else {
			echo 'error save data';
		}
	} else {
		echo '* completed the parameter above';
	}
} 
?>
<h3>Notifications List:</h3>
<table class="table">
	<thead>
		<tr>
			<th>No</th>
			<th>Next Schedule</th>
			<th>Title</th>
			<th>Message</th>
			<th>Remains</th>
			<th>User</th>
		</tr>
	</thead>
	<tbody>
		<?php $notificationCount =1; 
		$notificationList = $notification->listNotification(); 			
		while ($notif = $notificationList->fetch_assoc()) { 	
		?>
		<tr>
			<td><?php echo $notificationCount ?></td>
			<td><?php echo $notif['ntime'] ?></td>
			<td><?php echo $notif['title'] ?></td>
			<td><?php echo $notif['message'] ?></td>
			<td><?php echo $notif['nloop']; ?></td>
			<td><?php echo $notif['username'] ?></td>
		</tr>
		<?php $notificationCount++; } ?>
	</tbody>
</table>

We will implement method saveNotification() in class Notification.php.

function saveNotification(){	
	$insertQuery = "
		INSERT INTO ".$this->notificationTable."( `title`, `message`, `ntime`, `repeat`, `nloop`, `username`)
		VALUES(?,?,?,?,?,?)";
	$stmt = $this->conn->prepare($insertQuery);			
	$stmt->bind_param("sssiis",$this->title, $this->message, $this->ntime, $this->repeat, $this->nloop, $this->username);
	if($stmt->execute()){
		return true;
	}	 
	return false;				
}		

Step5: Handle Push Notifications

We will create a JavaScript file notification.js and implement function getNotification() to get notification details by making Ajax request to notification.php file. The function will also handle push notification functionality by checking permissions and display it.

function getNotification() {	
	if (!Notification) {
		$('body').append('*Browser does not support Web Notification');
		return;
	}
	if (Notification.permission !== "granted") {		
		Notification.requestPermission();
	} else {		
		$.ajax({
			url : "notification.php",
			type: "POST",
			success: function(response, textStatus, jqXHR) {
				var response = jQuery.parseJSON(response);
				if(response.result == true) {
					var notificationDetails = response.notif;
					for (var i = notificationDetails.length - 1; i >= 0; i--) {
						var notificationUrl = notificationDetails[i]['url'];
						var notificationObj = new Notification(notificationDetails[i]['title'], {
							icon: notificationDetails[i]['icon'],
							body: notificationDetails[i]['message'],
						});
						notificationObj.onclick = function () {
							window.open(notificationUrl); 
							notificationObj.close();     
						};
						setTimeout(function(){
							notificationObj.close();
						}, 5000);
					};
				} else {
				}
			},
			error: function(jqXHR, textStatus, errorThrown)	{}
		}); 
	}
}

Step6: Get Push Notification Details

We will create notification.php file and get logged in user notification details by calling method getNotificationByUser() to show the notification. The notification details has been updated after displaying notification by calling method updateNotification() from class Notification.php. The details of notification is returned as JSON data.

session_start(); 
include_once 'config/Database.php';
include_once 'class/Notification.php';
$database = new Database();
$db = $database->getConnection();
$notification = new Notification($db);
$array=array(); 
$rows=array(); 
$notification->username = $_SESSION['username'];
$result = $notification->getNotificationByUser(); 
$totalNotification = 0;
while ($userNotification = $result->fetch_assoc()) { 		
 $data['title'] = $userNotification['title'];
 $data['message'] = $userNotification['message'];
 $data['icon'] = 'https://webdamn.com/demo/build-push-notification-system-php-mysql-demo/avatar.png';
 $data['url'] = 'https://webdamn.com';
 $rows[] = $data;
 $nextime = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))+($userNotification['repeat']*60));
 $notification->nexttime = $nextime;
 $notification->id = $userNotification['id'];
 $notification->updateNotification();
 $totalNotification++;
}
$array['notif'] = $rows;
$array['count'] = $totalNotification;
$array['result'] = true;
echo json_encode($array);

We will implement method getNotificationByUser() in class Notification.php.

function getNotificationByUser(){
	$query = "
		SELECT *
		FROM ".$this->notificationTable." 
		WHERE username= ? AND nloop > 0 AND ntime <= CURRENT_TIMESTAMP()";
	$stmt = $this->conn->prepare($query);				
	$stmt->bind_param("s", $this->username);	
	$stmt->execute();		
	$result = $stmt->get_result();		
	return $result;	
}	

We will implement method updateNotification() in class Notification.php.

function updateNotification() {		
	$updateQuery = "
		UPDATE ".$this->notificationTable." 
		SET ntime= ?, publish_date=CURRENT_TIMESTAMP(), nloop = nloop-1 
		WHERE id= ? ";		
	$stmt = $this->conn->prepare($updateQuery);	 		 
	$stmt->bind_param("si", $this->nexttime, $this->id);		
	if($stmt->execute()){
		return true;
	}	 
	return false;		
}	

You may also like:

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

16 thoughts on “Build Push Notification System with PHP & MySQL

    1. You can rest the notification close time in notification.js, currently it is set 5 seconds. thanks!

  1. Hi,
    Your demo works fine on my PC and it was really helpful.
    But when I try on my phone, I received the request for sending notifications, I accept… but never receives notifications.
    Any idea why?

    1. yes, it’s working in pc only, you will have to implement to work in mobile. I am also looking for the solution and update. thanks!

  2. It’s not working , message not received , I tried your demo also , in mobile no message receive

  3. Fatal error: Call to a member function bind_param() on a non-object in /srv/disk8/3093778/www/devlop1.atwebpages.com/class/User.php on line 28

Comments are closed.