Answer the question
In order to leave comments, you need to log in
How to pull data from database in real time?
I need to get new entries from the database (if anything, I'm creating a web chat).
I already know about a method like:
1) you need to make a function that checks for new records from the database every second. But, I think that this method will load the server and the PC, if there is another way that will display new data at the time of its creation!
Here is my current code:
app.js
// Socket Connect
io.on('connection', function (socket) {
console.log('Socket Run...')
// Send sms
socket.on('chat message', function(msg){
let sql = `INSERT INTO myDB VALUES(${msg})`;
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
})
io.emit('chat message', msg);
});
// Disconnect
socket.on('disconnect', function(){
console.log('Socket STOP!');
});
});
$(function () {
var socket = io();
$('form').submit((e) => {
e.preventDefault();
socket.emit('chat message', $('.m').val());
$('.m').val('');
return false;
});
socket.on('chat message', function(msg){
$('.sms').append($('<li>').text(msg));
});
});
Answer the question
In order to leave comments, you need to log in
make a function that checks for new records from the database every second. But I think that this method will load the server and PC. if there is some other way that displays new data at the time of its creation.
I would make a different logic. What for constantly to pull mysql? Mysql should only return data once, when the page is loaded. The rest of the messages should be delivered directly to users via socket.io . And already at this stage, the data should be written in parallel to mysql.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question