Push Notification System with PHP & MySQL Demo [updated – 2021]

Today, We want to share with you notification in php demo.In this post we will show you notification alert in php mysql, Web Push Notification is a feature to send customized clickable message to display in subscribed customer’s web browsers like Chrome, Firefox, Safari etc. hear for php notification alert when new record is inserted we will give you demo and example for implement.In this post, we will learn about How To Send Push Notification Using FCM Using Php with an example.

The push notifications are useful to update customer’s with specific news, chat, new email and time bound information like offers etc.

Creating Real Time Notification System in PHP and AJAX

As we will cover this tutorial with live example to implement web push notification system with PHP and MySQL, so the major files for this example is following.

  • index.php
  • login.php
  • manage_subscription.php
  • subscription.js
  • subscription.php
  • Push.php
  • logout.php

creating real time notification system in php and ajax

Step 1: Create Database Tables

First we will create MySQL database table subscription_customer to store customers for login to show subscription message to logged in customers.

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

We will also create a table subscript to store notification details.

CREATE TABLE `subscript` (
`id` int(11) NOT NULL,
`title` varchar(250) NOT NULL,
`subscription_msg` text NOT NULL,
`subscription_time` datetime DEFAULT NULL,
`subscription_repeat` int(11) DEFAULT '1',
`subscription_loop` int(11) NOT NULL DEFAULT '1',
`publish_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`customername` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2: Create User Login

Now we will create customer login page to allow customer login to show subscriptions to logged in customers.

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

we will implement customer login functionality on form lsubmit.

<?php
if (!empty($_POST['customername']) && !empty($_POST['pwd'])) {
include ('Push.php');
$push = new Push();
$customer = $push->loginUsers($_POST['customername'], $_POST['pwd']);
if(!empty($customer)) {
$_SESSION['customername'] = $customer[0]['customername'];
header("Location:index.php");
} else {
$loginError = "Invalid customername or password!";
}
}
?>

Step 3: Add Notification and Display List

manage_subscription.php
In manage_subscription.php file, we will create HTML for adding new subscription by Administrator.

<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>Message</td>
<td><textarea name="msg" cols="50" rows="4" class="form-control" required></textarea></td>
</tr>
<tr>
<td>Broadcast time</td>
<td><select name="time" 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="customer" class="form-control">
<?php
$customer = $push->listUsers();
foreach ($customer as $key) {
?>
<option value="<?php echo $key['customername'] ?>"><?php echo $key['customername'] ?></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>

we will implement functionality to save new subscriptions to database table on form submit.

<?php
if (isset($_POST['submit'])) {
if(isset($_POST['msg']) and isset($_POST['time']) and isset($_POST['loops']) and isset($_POST['loop_every']) and isset($_POST['customer'])) {
$msg = $_POST['msg'];
$time = date('Y-m-d H:i:s');
$loop= $_POST['loops'];
$loop_every=$_POST['loop_every'];
$customer = $_POST['customer'];
$isSaved = $push->saveNotification($msg,$time,$loop,$loop_every,$customer);
if($isSaved) {
echo '* save new subscription success';
} else {
echo 'error save data';
}
} else {
echo '* completed the parameter above';
}
}
?>

Now we will display list of add subscriptions.

<h3>Notifications List:</h3>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>Next Schedule</th>
<th>Message</th>
<th>Remains</th>
<th>User</th>
</tr>
</thead>
<tbody>
<?php $a =1;
$subscriptList = $push->listNotification();
foreach ($subscriptList as $key) {
?>
<tr>
<td><?php echo $a ?></td>
<td><?php echo $key['subscription_time'] ?></td>
<td><?php echo $key['subscription_msg'] ?></td>
<td><?php echo $key['subscription_loop']; ?></td>
<td><?php echo $key['customername'] ?></td>
</tr>
<?php $a++; } ?>
</tbody>
</table>

Step 4: Broadcast Notification

subscription.js
In subscription.js file, we will create function showNotification() to make Ajax request to subscription.php to get subscription details for logged in customer and execute subscription.


function showNotification() {
if (!Notification) {
$('body').append('<h4 style="color:red">*Browser does not support Web Notification</h4>');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
$.ajax({
url : "subscription.php",
type: "POST",
success: function(data, textStatus, jqXHR) {
var data = jQuery.parseJSON(data);
if(data.result == true) {
var data_subscription = data.subscript;
for (var i = data_subscription.length - 1; i >= 0; i--) {
var theurl = data_subscription[i]['url'];
var subscriptikasi = new Notification(data_subscription[i]['title'], {
icon: data_subscription[i]['icon'],
body: data_subscription[i]['msg'],
});
subscriptikasi.onclick = function () {
window.open(theurl);
subscriptikasi.close();
};
setTimeout(function(){
subscriptikasi.close();
}, 5000);
};
} else {
}
},
error: function(jqXHR, textStatus, errorThrown) {}
});
}
};

Then we will call function showNotification() to execute subscription on every 20 seconds. When customer logged in, it will make ajax request to check for logged in customer and display subscription message accordingly.

$(document).ready(function() {
showNotification();
setInterval(function(){ showNotification(); }, 20000);
});

Step 5: Get Notification Details

subscription.php
In subscription.php file, we will get logged in customer’s subscription details and returned as json response as this file called by Ajax request.

<?php
SESSION_START();
include ('Push.php');
$push = new Push();
$array=array();
$rows=array();
$subscriptList = $push->listNotificationUser($_SESSION['customername']);
$record = 0;
foreach ($subscriptList as $key) {
$data['title'] = $key['title'];
$data['msg'] = $key['subscription_msg']; 
$data['icon'] = 'https://www.pakainfo.com/demo/push-subscription-system-with-php-mysql-demo/avatar.png';
$data['url'] = 'https://www.pakainfo.com';
$rows[] = $data;
$nextime = date('Y-m-d H:i:s',strtotime(date('Y-m-d H:i:s'))+($key['subscription_repeat']*60));
$push->updateNotification($key['id'],$nextime);
$record++;
}
$array['subscript'] = $rows;
$array['count'] = $record;
$array['result'] = true;
echo json_encode($array);
?>

Step 6: Create Get and Set Push Notification functions

Push.php
In Push.php file, we will create functions to perform push subscription functionality like get subscription details, save subscription, update etc.

<?php
class Push{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $database = 'pakainfo_demos';
private $subscriptTable = 'subscript';
private $customerTable = 'subscription_customer';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
private function getData($query_SQQ) {
$result = mysqli_query($this->dbConnect, $query_SQQ);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function listNotification(){
$query_SQQ = 'SELECT * FROM '.$this->subscriptTable;
return $this->getData($query_SQQ);
}
public function listNotificationUser($customer){
$query_SQQ = "SELECT * FROM ".$this->subscriptTable." WHERE customername='$customer' AND subscription_loop > 0 AND subscription_time <= CURRENT_TIMESTAMP()"; return $this->getData($query_SQQ);
}
public function listUsers(){
$query_SQQ = "SELECT * FROM ".$this->customerTable." WHERE customername != 'admin'";
return $this->getData($query_SQQ);
}
public function loginUsers($customername, $password){
$query_SQQ = "SELECT id as customerid, customername, password FROM ".$this->customerTable." WHERE customername='$customername' AND password='$password'";
return $this->getData($query_SQQ);
}
public function saveNotification($msg, $time, $loop, $loop_every, $customer){
$query_SQQ = "INSERT INTO ".$this->subscriptTable."(subscription_msg, subscription_time, subscription_repeat, subscription_loop, customername) VALUES('$msg', '$time', '$loop', '$loop_every', '$customer')";
$result = mysqli_query($this->dbConnect, $query_SQQ);
if(!$result){
return ('Error in query: '. mysqli_error());
} else {
return $result;
}
}
public function updateNotification($id, $nextTime) {
$sqlUpdate = "UPDATE ".$this->subscriptTable." SET subscription_time = '$nextTime', publish_date=CURRENT_TIMESTAMP(), subscription_loop = subscription_loop-1 WHERE id='$id')";
mysqli_query($this->dbConnect, $sqlUpdate);
}
}
?>

I hope you get an idea about Notification system using php and mysql.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.