0

I need help with this problem I got. I have login script that crashes node if the username or password isn't in the database, here the code:

/* Login */ exports.login = function(req, res){ var post = req.body; var mysql = require('mysql'); var db = mysql.createConnection({ host : 'localhost', user : 'root', password : 'root', database : 'node01', }); var selectStmt = 'SELECT * FROM users WHERE name = "' + post.user +'"'; db.connect(); db.query(selectStmt, function(err, rows, fields) { if(err) throw err; else if(rows[0].name == post.user && rows[0].password == post.password){ req.session.auth_id = rows[0].id; req.session.user = rows[0].name; res.redirect('/adminindex'); } else res.redirect('/admin'); }); db.end(); }; 

and the error I get

TypeError: Cannot read property 'name' of undefined
at Query.exports.login [as _callback] (../node-project01/routes/login.js:18:19)
at Query.Sequence.end (../node-project01/node_modules/mysql/lib/protocol/sequences/Sequence.js:66:24)
at Query._handleFinalResultPacket (../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:138:8)
at Query.EofPacket (../node-project01/node_modules/mysql/lib/protocol/sequences/Query.js:122:8)
at Protocol._parsePacket (../node-project01/node_modules/mysql/lib/protocol/Protocol.js:165:24)
at Parser.write (../node-project01/node_modules/mysql/lib/protocol/Parser.js:60:12)
at Protocol.write (../node-project01/node_modules/mysql/lib/protocol/Protocol.js:32:16)
at Socket.ondata (stream.js:38:26)
at Socket.EventEmitter.emit (events.js:96:17)
at TCP.onread (net.js:396:14)

Any ideas on how to fix this?

1
  • Don't put code and error on a separate site - put them in your question! Commented Dec 6, 2012 at 15:42

1 Answer 1

2

Well, considering that your question is from December, I imagine that you have already solved the problem. However, your problem is probably because your query have no results, then 'rows[0]' is undefined. before using the 'rows' variable you always should test if there is any result, like:

if (rows.length > 0) { // your code here } 

regards,

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.