node js Insert into mysql variable not work - javascript

I am using MySql with node.js
i have this query and it works:
connection.query('insert into username (name) values ("msg")', function(err, rows, fields) {
if(!err) {
} });
it inserts the string "msg", not the value of the variable msg, but when I want to insert the variable this does not work:
connection.query('insert into username (name) values '+ msg, function(err, rows, fields) {
if(!err) {
} });
for example:
var msg = "hello world!";

You are missing the parenthesis and the quotes that make a valid insert statement in the second case. You are building a sql statement that looks like this:
'insert into username (name) values hello world'
which is malformed. Use the util module to make your string formatting easier:
var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err, rows, fields) {
if(!err) {
} });

try this code
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'db_name'
});
connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
if (err) throw err;
});

Related

How to insert sql query data in array using node js

How to insert sql query data in array using node js
i want to insert data in mysql database and also in array using node js
please give proper solution.
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "root#123",
database: "abc"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var temp = [1, 2];
sql =
"INSERT INTO student(`name`, `email`) VALUES (?) ";
conn.query(sql, [temp], function (err, result) {
console.log(temp);
if (err) throw err;
conn.end();
});```
Hey please change your code like this...
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "root#123",
database: "abc"
});
conn.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
var temp = [1, 2];
var sql =
"INSERT INTO student(`name`, `email`) VALUES (?,?) ";
conn.query(sql, temp, function (err, result) {
console.log(temp);
if (err) throw err;
conn.end();
});

Building a massive query based on single query [duplicate]

I'm using nodejs 10.26 + express 3.5 + node-mysql 2.1.1 +
MySQL-Server Version: 5.6.16.
I got 4 DELETE's and want only 1 Database Request, so i connected the DELETE commands with a ";"... but it fails always.
var sql_string = "DELETE FROM user_tables WHERE name = 'Testbase';";
sql_string += "DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase';";
sql_string += "DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase';";
connection.query(sql_string, function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
It throws this error:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase';DELETE FR' at line 1
But if i paste this SQL in PhpMyAdmin it is always successful...
If i write it in single query's its succeed, too.
connection.query("DELETE FROM user_tables WHERE name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_structure WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_rules WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
connection.query("DELETE FROM user_tables_columns WHERE parent_table_name = 'Testbase'", function(err, rows, fields) {
if (err) throw err;
res.send('true');
});
});
});
});
Thanks for help!
I guess you are using node-mysql. (but should also work for node-mysql2)
The docs says:
Support for multiple statements is disabled for security reasons (it
allows for SQL injection attacks if values are not properly escaped).
Multiple statement queries
To use this feature you have to enable it for your connection:
var connection = mysql.createConnection({multipleStatements: true});
Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.
Example
connection.query('SELECT ?; SELECT ?', [1, 2], function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
So if you have enabled the multipleStatements, your first code should work.
Using "multiplestatements: true" like shown below worked for me
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: '',
multipleStatements: true
});
connection.connect();
var sql = "CREATE TABLE test(id INT DEFAULT 1, name VARCHAR(50));ALTER TABLE test ADD age VARCHAR(10);";
connection.query(sql, function(error, results, fields) {
if (error) {
throw error;
}
});
To Fetch Data from DB(SQL), the following function would work accurately
router.get('/', function messageFunction(req, res){
//res.send('Hi Dear Rasikh, Welcome to Test Page.') //=> One Way
dbConn.query('SELECT COUNT(name) as counted, name, last_name, phone, email from students',
function (err, rows, fields) { // another Way
if (err) throw err
dbConn.query('SELECT name, author from books',
function (err, rowsBook, fields) { // another Way
if (err) throw err
// console.log('The counted is: ', rows[0].counted); //=> Display in console
// res.send('Hi Dear Rasikh, Welcome to Test Page.'+ rows[0].counted) //=> Display in blank page
res.render('main/index',{data:rows, myData:rowsBook});
})
});
});

Passing BCrypt hash to another function

I want to encypt a password using BCrypt and then pass it to another function to store it in DB. The problem is that I can't pass it successfuly. I receive an error: "ReferenceError: hashedPass is not defined" on write-to-db.js:18
This part of code encrypts and has to send the hash to "write.registerUser()"
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser(function(data, fName, lName, email, role, date, hashedPass){
return();
});
});
});
That is write-to-db.js where I try to save to DB but fail:
registerUser(Callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+fName+"', '"+lName+"', '"+email+"', '"+role+"', '"+date+"', '"+1+"', '"+hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
Callback(result);
});
}
Any ideas?
change your registerUser function to:
registerUser(params, callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+params.fName+"', '"+params.lName+"', '"+params.email+"', '"+params.role+"', '"+params.date+"', '"+1+"', '"+params.hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
callback(result);
});
}
and change your hash generating code to:
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser({
data,
fName,
lName,
email,
role,
date,
hashedPass
}, function(results){
console.log(results)
return();
});
});
});
WARNING: this SQL query is vulnerable to SQL INJECTION. You would be wise to use prepared statements or an ORM.

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?
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.
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

Undefined query function

so I'm currently using the following code to execute queries;
var mysql = require('mysql');
var config = require('./config');
var pool = mysql.createPool(config.mysql);
function query(statement){
return new Promise(function(resolve, reject){
pool.getConnection(function(err, connection) {
if(err) reject(err);
connection.query(statement, function(err, row){
connection.release();
if(err){
reject(err);
}
resolve(row);
})
});
});
}
module.exports = {
pool: pool,
query: query
};
Whenever the query function is called it results in a undefined error;
TypeError: Cannot read property 'query' of undefined
I'm quite out of ideas why this could be, this would be connection.getConnection is not returning a proper connection, would this mean my credentials are wrong in my createPool function?
config.mysql
mysql: {
host: 'localhost',
user: 'root',
password: '',
database: 'site',
connectionLimit : 10,
multipleStatements : true
}
The problem is on the following line you are passing in the query function when you should be passing in a string.
connection.query(query, function(err, row){
query in that case should be a string. But you defined query as a function (function query(){)
If you change the line to something LIKE the following this should work.
connection.query("SELECT * from Users", function(err, row){

Categories