Nicholas Hendricks Nicholas Hendricks - 1 month ago 25
HTML Question

printing mysql database to a html page in socket.io and node.js

I am trying to be able to print mysql data to a html page just to test it so i can start learning

Upadated Code

here is what i have tried on my server.js

var mysql = require("mysql");
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendfile('testsql.html');
//res.sendfile('/login/');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "users"
});


io.on('connection', function (socket) {

console.log('a client connected');

con.query('SELECT * FROM users',function(err,rows){
if(err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
socket.emit('showrows', rows);
});



});


**And Here is My Client Code **

<!doctype html>
<html>
<head>
<title>Testing socket.io</title>
</head>
<body>
<h1 id="socketio"> not connected </h1>
<div id="display"> </div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('connect', function() {
document.getElementById("socketio").innerHTML = "socket connected";
});
socket.on('showrows', function(dbData) {
document.getElementById("display").innerHTML = dbData;
});
</script>
</body>
</html>


the client is showing that it is connecting to the server but it is not displaying the query result on the client

Answer

You can try the following changes:

in the server:

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "password",
    database: "users"
});


io.on('connection', function (socket) {

    console.log('a client connected');

    con.query('SELECT * FROM users',function(err,rows){
      if(err) throw err;
      console.log('Data received from Db:\n');
      console.log(rows);
      socket.emit('showrows', rows);
    });



 });

in the client:

<!doctype html>
<html>
  <head>
    <title>Testing socket.io</title>
  </head>
  <body>
    <h1 id="socketio"> not connected </h1>
    <div id="display"> </div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      socket.on('connect', function() {
        document.getElementById("socketio").innerHTML = "socket connected";
      });
      socket.on('showrows', function(rows) {
        var html='';
        for (var i=0; i<rows.length; i++) {
          html += rows[i].firstname + ' ' + rows[i].lastname + '<br>';
        }  
        document.getElementById("display").innerHTML = html;
        console.log(rows);
      });
    </script>
  </body>
</html>