mysql请求在node.js应用程序中不起作用

时间:2014-01-21 18:29:09

标签: mysql node.js socket.io chat messaging

我正在使用socket.io node.js和mysql开发聊天,我有一个问题,即所有mysql查询都不起作用。我从这里https://github.com/felixge/node-mysql尝试了一些sql查询的例子,但是他们工作了,但我的查询不行。也许问题是socket.on函数,但我不知道。日志也不起作用。请帮帮我!

var http = require('http');

var mysql      = require('mysql');

var connection = mysql.createConnection({
 host     : 'localhost',
 user     : 'root',
 password : '',
 database : 'lc',
});

var io = require('socket.io').listen(8080); 

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

function escapeHtml(str) {
  return String(str)
      .replace(/&/g, "&")
      .replace(/</g, "<")
      .replace(/>/g, ">")
      .replace(/"/g, "")
      .replace(/'/g, "'")
       .replace(/\//g, "⁄");
}

socket.on('connect_user', function(login,password, idUserGet){
    var sql    = 'SELECT * FROM users WHERE login = ' + connection.escape(login) + ' AND       password = ' + connection.escape(password) + ' ';
    connection.query(sql, function(err, rows) {
        if(rows.length > 0) {

            socket.userGet = idUserGet;
            socket.userSend = rows[0].id;


            console.log(socket.userSend+' has been logined ');
            socket.join(socket.userSend);

            // Мое имя.
            socket.user = rows[0].login;
        } 
    });


socket.on( 'msg', function(msg) {
    // htmlencode
    msg = escapeHtml(msg); 

    // Unixtime
    milliseconds = parseInt(new Date().getTime()/1000);
    var post  = {user_send: socket.userSend, user_get: socket.userGet, text: msg, date: milliseconds};
    query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
        update = connection.query(sql);
    });





    console.log(' usersend id:  ' +socket.userSend +'  user get:  ' + socket.userGet + ' ');
     socket.broadcast.to(socket.userGet).json.emit('incMsg',{'userSend': socket.userSend, 'name': socket.user, 'text': msg, 'time': time })
});
});
});

0 个答案:

没有答案