Nodejs user authentication sql command

时间:2015-07-31 20:01:21

标签: mysql node.js

i am trying to make user authentication form in node.js with express.

currently i am using this query to insert in my db.

var  username = req.body.username;
var  password = req.body.password;


connection.query('USE one');
  connection.query("INSERT INTO users(id,name,pass) VALUES (1,"+ username +","+password+")", 
    function (err, result) {
        if (err) throw err;
    }
);

my db structure is

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(30) | NO   |     | NULL    |                |
| pass  | varchar(20) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Please help i am getting an error:-

throw err; ^ Error: ER_BAD_FIELD_ERROR: Unknown column 'jjhk' in 'field list'

2 个答案:

答案 0 :(得分:-1)

connection.query("INSERT INTO users(id,name,pass) VALUES (1,"+ username +","+password+")"

should be

connection.query("INSERT INTO users(id,name,pass) VALUES (1,'"+ username +"','"+password+"')"

答案 1 :(得分:-1)

看起来你正在使用node-mysql模块。为了避免SQL注入并使用正确的字符串转义,您的查询应如下所示:

var  username = req.body.username;
var  password = req.body.password;


connection.query('USE one');
  connection.query("INSERT INTO users(id,name,pass) VALUES (1,?,?)", [username, password],
    function (err, result) {
        if (err) throw err;
    }
);