Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'     
})


connection.connect();
 //var querydata = +"'"+data.RegUsername + "','"+data.RegPassword+"'" 
  connection.query("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES ?", data.RegUsername,+","+ data.Regpassword , function(err,rows,fields){
   if (err) throw err;
    })
  });*/

This query causes an error, what am I doing wrong?

like image 534
AlexDoe Avatar asked Dec 25 '22 00:12

AlexDoe


2 Answers

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.

like image 58
Dave Avatar answered Dec 28 '22 08:12

Dave


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

like image 43
huhushow Avatar answered Dec 28 '22 07:12

huhushow