Add variables to columns (Mysql)

Asked

Viewed 284 times

2

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

Codigo Test

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'
  • What is the name of the variable(s) (eis) and what is the name(s) of the column(s))?

  • spine someparam and the variable as exemplified in the code "varToParam"

  • Okay, so test like this: var sql = "INSERT INTO sometable (someparam) VALUES (" + varToParam + ")";

  • 1

    Already worked thanks @Sergio

1 answer

2


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

You can use the + 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 string template:

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

Be careful to always process the data before entering 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");
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.