0

Thank you all in advance!

So, I have an internal system running for my company that administrates data. Sometimes that data it's modify or I add new data, and I need to notify the users when this happens. I had created a notification system that shows what´s new in the database in a modal window when users click on a bell-shape link (kinda like the google's notification bell). The thing is that is a static link and I would like it to switch color or for another icon when I insert or modify stuff in the database, then switch back when the users see it. Maybe turn red when changes are made and back to white when seen by users.

First of, I must mention I have 3 tables in the database; Users, Listing, and Notifications. The notifications table is to notify users when data is changed or new data is added to the listing table, this through a form I created.

So far, my code goes like this:

This is the code for the users:

<?php
session_start();
if (!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]);
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]);
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]);
include "scripts/connect.php";
$sql = mysql_query("SELECT * FROM users WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount == 0){
    echo "The login info you entered does not exist in the database.";
exit();
}
$header ="";
while ($row = mysql_fetch_array($sql)){
$name = $row["name"];
$accounttype = $row["accounttype"];
if($accounttype == "a"){
    include_once "menu_a.php";
}else{
    include_once "menu_b.php";
}
}
?>

Note that there are two headers in the index page (menu_a.php and menu_b.php) that contain a different navigation menu. This is because there are two types of user accounts; "a" who can only see the listing and certain stuff, and "b" (me) who has acces to administration tasks.

Now, in both headers (menu_a.php and menu_b.php), he link for all users to see what's new looks like this:

<a href="#openModal"><i class="fa fa-bell" style="color:#fff;"></i></a>

Then, the display of notifications goes in a file named "navigation_table.php". Which opens in a modal window from every page from the site by calling "include_once ("notificaciones_table.php");". That code goes like this:

<?php
$listnotif = "";
$sql = mysql_query("SELECT * FROM notificatios ORDER BY date DESC LIMIT 15");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
    $type = $row["type"];
    $description = $row["description"];
    $date = ucwords(strftime("%A %e/%m/%Y - %l:%M", strtotime($row["date"])));
    $listnotif .= "<tr><td><small>$date</small></td><td>$type</td><td>$description</td><tr>";
}
    } else {
    $listnotif = "<tr><td colspan='3'>There are no notifications</td></tr>";
    }
?>

<table>
<tr>
    <th>Date</th>
    <th>Type</th>
    <th>Description</th>
</tr>
<?php echo $listnotif; ?>
</table>

Then, in a page named "notif_admin.php", I display all notifications I've created so I can administrate them, and a form to insert new data into the notificatios table. The code looks like this:

<?php 
$delete = "";
if (isset($_GET['deleteid'])) {
    $delete .= 'You sure you want to delete this entry? <a href="notif_admin.php?yesdelete=' . $_GET['deleteid'] . '">&ensp;<b>Yes</b></a> - <a href="notif_admin.php"><b>No</b></a></div>';
}
if (isset($_GET['yesdelete'])) {
$id_to_delete = $_GET['yesdelete'];
$sql = mysql_query("DELETE FROM notifications WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
}
?>
<?php
if (isset($_POST['type'])){
    $type = mysql_real_escape_string($_POST['type']);
    $description = mysql_real_escape_string($_POST['description']);

    $sql = mysql_query("INSERT INTO notifications (type,description,date) VALUES('$type','$description',now())") or die (mysql_error());
}
?>
<?php
$notification = "";
$sql = mysql_query("SELECT * FROM notifications ORDER BY date DESC");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
    $id = $row["id"];
    $type = $row["type"];
    $description = $row["description"];
    $date = ucwords(strftime("%A %e/%m/%Y - %l:%M", strtotime($row["date"])));
    $notification .= "<tr><td><a href='notif_admin.php?deleteid=$id'><span class='fa fa-trash-o'></span></a></td><td>$date</td><td>$type</td><td>$description</td></tr>";
}
} else {
$notification = "<tr><td>No stuff here</td></tr>";
}
?>

<table>
<tr>
    <th>delete</th>
    <th width="200">Date</th>
    <th>Type</th>
    <th>Description</th>
</tr>
<?php echo $notification; ?>
</table>
</div>

<form action="notif_admin.php" enctype="multipart/form-data" name="myForm" id="myForm" method="post">
<table>
<tr>
<td width="150">Type</td>
<td>
    <select name="type" id="type">
        <option selected="selected">Select</option>
        <option value="Addition">Additio</option>
        <option value="Removal">Removal</option>
        <option value="Modification">Modification</option>
        <option value="Correction">Correction</option>
        <option value="General">General</option>
    </select>
</td>
</tr>
<tr>
<td>Description</td>
<td><input name="description" id="description" type="text"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="button" id="button" type="submit" value="Add Notification" class="boton"></td>
</tr>
</table>
</form>

This image for a better reference: Switch notification icon when new insert into database and when seen by user

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
Victor Vizcaino
  • 11
  • 1
  • 2
  • 10
  • Thanks for the code. You only forgot to mention what your actual question is. What is wrong with this code? – GolezTrol Jun 11 '15 at 19:51
  • You can use JavaScript and Ajax to check every 30 secs or something if there are news for the current user. Add an extra column to the notifications table, false if the notification has not been seen, true when the users sees it. – Jose Manuel Abarca Rodríguez Jun 11 '15 at 19:51
  • @GolezTrol, thank you for taking the time. I would like to know how can I make the notification icon switch, let's say to red, when I insert a new entry into the notifications table, and then back to white when it's been seen by a user. – Victor Vizcaino Jun 11 '15 at 19:55
  • Sidenote: I must stress that this entire code is open to SQL injection. Best to use prepared statements. Even though you are using `mysql_real_escape_string()` that still isn't bullet proof. See this Q&A on the subject http://stackoverflow.com/q/5741187/ – Funk Forty Niner Jun 11 '15 at 20:00
  • Jose, that sounds interesting. Could you provide an exapmle of how to accomplish that? I have little knowledge on JavaScript and Ajax. – Victor Vizcaino Jun 11 '15 at 22:47

2 Answers2

0

If you want real time notifications there are a few options.

  1. You can use Server Sent Events.
  2. You can poll your server using AJAX on the front end.

Provided you're using JQuery, that would look something like this.

setInterval(function() {
    $.get('/notification_url', function(res) {
        $('.fa-bell').css({'color': 'red'});
    });    
}, 1000);

This will poll some page on your server every second to check for updates.

You've got options, but either way you're going to need to update it via Javascript.

Scheda
  • 526
  • 5
  • 11
0

previous answer is good but I think is better to increase interval between ajax requests 1 second is very low interval and will congest, maybe conflict.. make it at least 5 seconds of interval between requests

var interval = setInterval(function() {
    $.get('/get_xyz_status_color.php?anyparam=paramvalue', function(colorResponse) {
        $('.fa-bell').css({'color': colorResponse});
    });    
}, 1000);

if you want to update many status, I recomend you to output a json with every status at the same request, to not cause excessive requests

So I recomend use $.getJSON instead of $.get

var interval = setInterval(function() {
    $.getJSON(url,function(response){
        $('.stat1').css({'color': response.status1});
        $('.stat2').css({'color': response.status2});
        ...
    });
}, 1000);
Hugo Ferreira
  • 184
  • 13