sauletasmiestas
sauletasmiestas

Reputation: 438

node.js javascript mysql query wait unitl next row is inserted

Is there are any ways to stop javascript query on mysql table and wait until next row is inserted?

For example using function:

var query = connection.query('SELECT * FROM table');

I want to read all rows in table, display them and wait until next row is inserted, read inserted row and wait until other is inserted and so on...

Basically it should read table which is updated every time other table gets update from PHP or other script (trigger events).

I can not find any information about cursor sliding in javascript mysql query maybe there are some articles about it?

Upvotes: 4

Views: 1788

Answers (1)

Jason Brumwell
Jason Brumwell

Reputation: 3550

You could poll for the answer like so, api made up as I've never used the mysql library for node.

Row Count Interval
var connection = ..., lastCount;

funciton mysqlPoll() {
    var query = connection.query('SELECT count(field) as count FROM table');

    query.exec(function(result) {
        if (result.count != lastCount) {
            //Select all the rows here using offset to skip the already processes
            //process them
            lastCount = result.count;
        }
    });
}

setInterval(mysqlPoll, 500); //every 1/2 second

Better if you have a primary auto-inc key Interval

var connection = ...,
    lastCount = 0;

funciton mysqlPoll() {
    var query = connection.query('SELECT * FROM table WHERE primaryId > '+lastCount);

    query.exec(function(result) {
        if (result.count != lastCount) {
            //Select all the rows here using offset to skip the already processes
            //process them
            lastCount = lastResultsPrimaryId;
        }
    });
}

setInterval(mysqlPoll, 500); //every 1/2 second

Another option would be to open a socket, (net, http, etc), on node.js and ping it from the php script to trigger an update.

Hope that helps

Upvotes: 2

Related Questions