Skip to content Skip to sidebar Skip to footer

Node-mysql Insert Query With Two Values?

This is my current javascript. var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root', database: 'codify', port: '8889'

Solution 1:

What you're doing wrong is that you're trying to concatenate your two values into a single string and have that string substituted into your single ?. If you're using a single ?, you need to pass in an object where the object's parameters are the same as the database field names.

I'd do it like this:

let payload = {
    UsernameDB: data.RegUsername,
    PasswordDB: data.Regpassword
};

connection.query("INSERT INTO Codify SET ?", payload, function(err, rows) {

});

You can also do it like this with an array instead of an object:

let sql = "INSERT INTO Codify (UsernameDB, PasswordDB) VALUES (?, ?)";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {

});

or like this:

let sql = "INSERT INTO Codify SET UsernameDB = ?, PasswordDB = ?";
connection.query(sql, [ data.RegUsername, data.Regpassword ],  function(err, rows) {

});

But I find using a single ? along with an object is more readable.

Solution 2:

placeholder ( ? character) will escape your querydata for avoid sql-injection. cause you don't use combined string for query. use placeholders to each inserted value. like

("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES (?,?)", [data.RegUsername,data.Regpassword] , function () )

check nodejs mysql driver document here

Post a Comment for "Node-mysql Insert Query With Two Values?"