Add variables to columns (MySQL)

2

I have a question, is it possible to add variables in a column?

Test Code

var sql = "INSERT INTO sometable (someparam) VALUES (varToParam)";
con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("test");
});

Error

Error: ER_BAD_FIELD_ERROR: Unknown column 'varToParam' in 'field list'
    
asked by anonymous 31.08.2017 / 20:16

1 answer

2

If varToParam is a variable with a value inside that you want to insert inside the query string, then you have to concatenate that value.

You can use + which is the concatenation operator or template strings.

Concatenating:

var varToParam = 4862349862435;
var sql = "INSERT INTO sometable (someparam) VALUES (" + varToParam + ")";
// vai dar: INSERT INTO sometable (someparam) VALUES (4862349862435)

With template string:

var varToParam = 4862349862435;
var sql = 'INSERT INTO sometable (someparam) VALUES (${varToParam})';
// vai dar: INSERT INTO sometable (someparam) VALUES (4862349862435)

Be careful to always treat the data before inserting it into the database. This library has a function for this mysql.escape that can be used like this:

var varToParam = 4862349862435;
varToParam = mysql.escape(varToParam);
var sql = "INSERT INTO sometable (someparam) VALUES (" + varToParam + ")";

Or so, with the library API for this:

var sql = "INSERT INTO sometable (someparam) VALUES (??)";
con.query(sql, [varToParam], function (err, result) {
    if (err) throw err;
    console.log("test");
});
    
31.08.2017 / 20:36