Page 1 of 1

Using MySQL wtih websockets

Posted: Wed Jun 13, 2012 12:56 am
by ShawnSwander
So I have this function that runs well and sends the client back the results I found it in my console as an object named rows with properties but I couldn't address it
from my snippet server.js...

Code: Select all

 socket.on ('login', function (name, password){      
      connection.escape(name);
      connection.escape(password);
      connection.connect();
      sql = "SELECT * FROM `playeraccounts` WHERE `name` = '"+name+"' AND `password` = '"+password+"'";
      connection.query(sql, function(err, rows, fields) {
         if (err) throw err;
            //result stored in rows varriable
            console.log('Query result: ', rows);
            //socket.emit('loginresult', rows); //returns object with fields rows.name="test"...
            socket.emit('loginresult', rows);
      });
      connection.end();
   });
right now I just catch it with this in index.html

Code: Select all

socket.on('loginresult', function (rows) {
   ig.game.player.rows = rows;
});
i have two questions about accessing this data.
1. How can I access a field from it on the server side (first code) so I can run a second query to pull a player from that users account.

2. How can I access individual fields from the ig.game.player.rows on client side

ig.game.player.rows.name didn't work...

Re: Using MySQL wtih websockets

Posted: Wed Jun 13, 2012 9:59 am
by ShawnSwander
So I dug up some info and wanted to post the answer to my own question here...

Given the socket function

Code: Select all

   socket.on ('login', function (username, password){      
      connection.escape(username);
      connection.escape(password);
      sql ="SELECT * FROM `playeraccounts` LEFT JOIN `players` USING(account_id) WHERE `username` = '"+username+"' AND `password` = '"+password+"'";
      connection.query(sql, function(err, rows, fields) {
         if (err) throw err;
         socket.emit('loginresult', rows);
      });
      connection.end();
   });
the player can catch the varriable passed (rows) and store it globally... its saved as an array of objects even if its only one row of code passed. if you want to access a single field you can do this by
rows[0].fieldname you can do this before its passed back on the websocket on the server side or after on the client.