16

I m using the node,express,mysql2 packages .When i m using console.log(rows) ,it is giving me following output:

[{"userid": "test","password": "test"}]

And here is my Code :

var application_root = __dirname,
express = require("express"),
mysql = require('mysql2');
path = require("path");
var app = express();

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123',
database: "bbsbec"
 });
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, "public")));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);
     console.log(rows);
   });

I just want to know that how can i parse this "rows" object so that i can retrive both userid and password .

3 Answers 3

28
[{"userid": "test","password": "test"}]

This is an Array of Objects. So: First loop over the array to get a single object and then extract its properties:

for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    console.log(row.userid);
}
Sign up to request clarification or add additional context in comments.

Comments

19

Try this (this is really basic):

   connection.query('SELECT * from pass', function(err, rows) {
     res.json(rows);

     var user = rows[0].userid;
     var password= rows[0].password;

   });

1 Comment

Remember that this only works with one row in the resultset. If there will be more, please use the second answer!
1

 connection.query('SELECT * from pass', function(err, rows) {
      data = rows[0];
     let user = data.userid;
     let password= data.password;
     res.json(rows);

   });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.