Home » Php » javascript – websockets and database updates (push on change)

javascript – websockets and database updates (push on change)

Posted by: admin July 12, 2020 Leave a comment

Questions:

I started to learn websockets today, since I want to have an architecture, with which I can get real-time updates.

I created my first websockets node.js and socket.io app, so I can communicate via javascript between a client and server. That works fine.

But I need something, that can communicate with a MySQL, so that for every change on a certain table, it has to tell the clients, that there is a change.

So I was thinking that the node.js server communicates with a PHP script that observes the database. But then I would also need long-pulling to request changes, so I could do it with ajax anyway, so it would be useless.

So my question: How can I achieve to get real-time data changes from a table of the database or from a certain query, which will send the update to all clients, that are connected in real-time, without long polling?

Thanks !

How to&Answers:

So my question: How can I achieve to get real-time data changes from a
table of the database or from a certain query…

There is a module to watch for MySQL events: mysql-events

Official Example :

var MySQLEvents = require('mysql-events');
var dsn = {
  host:     _dbhostname_,
  user:     _dbusername_,
  password: _dbpassword_,
};
var mysqlEventWatcher = MySQLEvents(dsn);
var watcher =mysqlEventWatcher.add(
  'myDB.table.field.value',
  function (oldRow, newRow, event) {
     //row inserted 
    if (oldRow === null) {
      //insert code goes here 
    }

     //row deleted 
    if (newRow === null) {
      //delete code goes here 
    }

     //row updated 
    if (oldRow !== null && newRow !== null) {
      //update code goes here 
    }

    //detailed event information 
    //console.log(event) 
  }, 
  'match this string or regex'
);

… which will send the update to all clients, that are connected in real-time,
without long polling?

You can use socket.io and prevent the initial http polling entirely by doing this on the client:

var socket = io({transports: ['websocket'], upgrade: false});

To avoid clients from using polling, add this line to the server:

io.set('transports', ['websocket']);

and to send the events to all connected (socket.io) clients from mysql-event use the following :

io.sockets.emit('db-event',eventDataObj)