I want to add a variable into mysql in nodejs - mysql

I insert a record in the database like this
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES ('2018-05-26', '23:00:00', 'blablabla')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
connection.end();
});
});
The above works but lets say I do
var ytime = '19:00:00';
var ydate = '2018-05-29';
var ytext = 'blabla';
connection.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES (ydate, ytime, ytext)";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
connection.end();
});
});
How do I do that? this gives just errors my node is v8.10.0

The latter didn't work because the sql statement did not interpret your ydate,ytime,ytext as variables but as a part of string. If you want to separate the statement and your data, you should do like this:
var ytime = '19:00:00';
var ydate = '2018-05-29';
var ytext = 'blabla';
var sql = "INSERT INTO xtable (x_date, x_time, x_text) VALUES (?,?,?)";
connection.query(sql, [ydate,ytime, ytext], function(err,result) {
...
});

You just switch your data to use placeholder values, then add the data separately:
connection.query(
"INSERT INTO xtable (x_date, x_time, x_text) VALUES (?, ?, ?)",
[ ydate, ytime, ytext ],
function (err, result) {
// ...
}
}
One thing to note about Node and MySQL is there's tools like Sequelize that make this a lot easier. Anything that supports Promises and async/await is almost always less fuss than a series of nested callbacks.

Related

Keep getting an error when trying to get the output from MySQL using Node JS [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});
})
});
});

MYSQL Node.js parse error and throw err error

throw err; // Rethrow non-MySQL errors
^
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 ''a', 'b', 'c'' at line 1
(I had entered a as the name,b as the username and c as the password in the form)
I can't figure out where the problem is.
db.js:
function createUser(name, username, password){
var sql = "INSERT INTO users (name,username,password) VALUES ?";
var values = [name, username, password];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log('inserted');
});
}
module.exports = {createUser};
relevant part of server.js:
app.post('/create', function(req,res) {
db.createUser(req.body.name,req.body.username,req.body.password);
res.status(200).send();
});
I think you just need additional square brackets around the values:
var sql = "INSERT INTO users (name,username,password) VALUES ?";
var values = [[name, username, password]];
con.query(sql, [values], function (err, result) { ... });
This mechanism is mostly meant to insert multiple rows. You could also separate the parameters:
var sql = "INSERT INTO users (name,username,password) VALUES (?, ?, ?)";
var values = [name, username, password];
con.query(sql, values, function (err, result) { ... });
You have to add for every variable a placeholder
function createUser(name, username, password){
var sql = "INSERT INTO users (name,username,password) VALUES (?,?,?);";
var values = [name, username, password];
con.query(sql, values, function (err, result) {
if (err) throw err;
console.log('inserted');
});
}
module.exports = {createUser};

How to return the response of Node.js mysql query connection

I am new at Node.js and I want to find something from database by using select query.
Here is my code.
var address = socket.request.client._peername.address;
var ip_addrss = address.split("::ffff:");
let mine = ip_addrss[1];
var location = iplocation_find(mine);
connection.connect( function () {
// insert user data with IP, location --- has got a status.
let stranger = "";
var values = [];
if (mine == null){
mine = "local server";
}
values.push(mine);
values.push('location');
var sql = "INSERT INTO user_list (IP_address, location) VALUES (?)";
connection.query(sql, [values], function (err, res){
if (err) throw err;
});
// control chatting connection between users
connection.query("SELECT IP_address FROM user_list WHERE status = ? AND location = ?", [0, "location"], function (err, res){
if (err) throw err;
stranger = res[0].IP_address;
console.log(stranger);
});
var room_users = [];
room_users.push(mine);
room_users.push(stranger);
console.log(room_users);
connection.query("INSERT INTO chatting_status (IP_client_1, IP_client_2) VALUES (?)", [room_users], function (err, res){
if (err) throw err;
console.log('inserted');
});
});
Now the problem is "stranger". It is not working anymore. Just always null.
Please tell me how I can return value in mysql query statement.
on my console, shows this.
[ 'local server', '' ]
127.0.0.1
inserted
[ '192.168.1.100', '' ]
127.0.0.1
inserted
Above, 'local server' and '192.168.1.100' are values of mine. And also '127.0.0.1' is the value of stranger only in query. But out of query it is just null.
You are using asynchronous operations with your .connect() and .query() calls. To sequence code with asynchronous callbacks like this, you have to continue the flow of control inside the callback and then communicate back errors or result via a callback.
You could do that like this:
let address = socket.request.client._peername.address;
let ip_addrss = address.split("::ffff:");
let mine = ip_addrss[1];
let location = iplocation_find(mine);
function run(callback) {
connection.connect( function () {
// insert user data with IP, location --- has got a status.
let values = [];
if (mine == null){
mine = "local server";
}
values.push(mine);
values.push('location');
var sql = "INSERT INTO user_list (IP_address, location) VALUES (?)";
connection.query(sql, [values], function (err, res){
if (err) return callback(err);
// control chatting connection between users
connection.query("SELECT IP_address FROM user_list WHERE status = ? AND location = ?", [0, "location"], function (err, res){
if (err) return callback(err);
let stranger = res[0].IP_address;
console.log(stranger);
let room_users = [];
room_users.push(mine);
room_users.push(stranger);
console.log(room_users);
connection.query("INSERT INTO chatting_status (IP_client_1, IP_client_2) VALUES (?)", [room_users], function (err, res){
if (err) return callback(err);
console.log('inserted');
callback(null, {stranger: stranger, room_users: room_users});
});
});
});
});
}
run((err, result) => {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
Personally, this continually nesting callback code is a drawback of writing sequenced asynchronous code with plain callbacks. I would prefer to use the promise interface to your database and write promise-based code using async/await which will allow you to write more linear looking code.

How to insert an object into SQL using nodejs

I'm trying to insert some string variables into a DB with nodeJS following parsing the text from the DOM.
I'm using cheerio for that , here's an example that I'm trying to write to my db, it type tests as a string and outputs a score out of 10 e.g 3.5 out of 10.
var kf = $('span.glyphicons.glyphicons-star').attr('title')
My code for the sql is as follows, I can't seem to find anywhere how to define the variable in the sql query line:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO juice (ratescore) VALUES ('" + con.escape(kf) + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});

Insert query in nodejs

I want to insert the value in this way any help me out this code.
It doesn't work for me . Error occurred as unknown column 'Fname1' in field list
app.post('/insert',function (req,res){
var Fname1=req.body.fname;
var Passwor1=req.body.pwd;
var sql="insert into test(Fname,Passwor) values(Fname1,Passwor1)";
con.query(sql,function(err,rows){
if(err) throw err;
res.send("Value has been inserted");
})
})
I don't want to insert in this way.
var data = {
Fname:req.body.fname,
Passwor:req.body.pwd
};
con.query("insert into test set ?",[data], function (err,rows){
if(err) throw err;
res.send("Value has been inserted");
})
Try this as your sql emit the Fname1 and Passwor1 as variables;
app.post('/insert',function (req,res){
var Fname1=req.body.fname;
var Passwor1=req.body.pwd;
var sql= "insert into test(Fname,Passwor) values ('"+Fname1+"', '"+Passwor1+"')";
con.query(sql,function(err,rows){
if(err) throw err;
res.send("Value has been inserted");
})
})
Your query should be like the following:
"insert into test(Fname,Passwor) values ('"+Fname1+"', '"+Passwor1+"')"