Query not working using node.js node-mysql - mysql

Whats wrong with my query? im having this error:
con.query(
'SELECT nick FROM channels WHERE room=1room',
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);
I tried this, and i have the same error:
var room = "1room";
con.query(
'SELECT nick FROM channels WHERE room=' + room,
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);

It is treating 1room as a variable, not a string. Wrap it in quotes and it should work.
con.query(
'SELECT nick FROM channels WHERE room="1room"',
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);
For your second example, you should get in the habit of escaping the variables you use in queries for security reasons (to prevent SQL injection).
var room = "1room";
con.query(
'SELECT nick FROM channels WHERE room=?',
[room],
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);

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 syntax error while running query in nodejs . Works fine on mysql workbench [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});
})
});
});

Anything wrong with how I'm using node-mysql's pool.getConnection?

node-mysql's pool.getConnection looks like this when used:
pool.getConnection(function(err, callback) {
callback(err, connection);
});
when used with exports.getConnection you type out:
var db = require('mysql');
var id = req.params.id;
db.getConnection(function(err, connection){
if(err) throw err;
connection.query('SELECT * FROM users WHERE id = ?', [id], function(err, data) {
connection.release();
if (err) throw err;
res.send(data);
});
});
I decided to abstract this out and in the mysql file I added:
exports.select = function(select, inserts, callback) {
pool.getConnection(function(err, connection) {
if (err) callback(err);
connection.query(select, inserts, function(err, response){
connection.release();
callback(err, response);
});
}
}
this way when I want to do a query I type:
db.select('SELECT * FROM users WHERE uid = ?', [id], function(err, data) {
if (err) throw err;
res.send(data);
});
I've tested this with and without inserts and with different queries. What I'm wondering is if there is anything dangerously wrong with it that I'm missing.
After Andrey Sidorov's comment I'm marking this as answered, not only because this is ok but it's not even necessary as the functionality is already built in. Thanks.

how to query mysql database with where clause using dynamic array

I'm trying to query mysql database with where clause as below.
Here popularTopicsNames is a dynamic array and its length and elements varies.
var scoreQuery=connection.query('SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN ('+popularTopicsNames+')', function(err,result,fields){
if(err) throw err;
else{
console.log(result);
}
If it's just an array then you're trying to pass it as a string, which won't work.
Try
var scoreQuery = connection.query("SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN ('" + popularTopicsNames.map(mysql.escape).join("','") + "')",
function(err, result, fields) {
if (err) {
throw err;
} else {
console.log(result);
}
});
This will solve the issue in a more readable way.
var scoreQuery = connection.query(`SELECT * FROM LEADERBOARD WHERE SUBTOPIC IN (?)`, [popularTopicsNames],
(err, result, _fields) => {
if (err) {
throw err;
} else {
console.log(result);
}
});

NodeJS Mysql Stop Server Crash on Error

I am using https://github.com/felixge/node-mysql
and everytime a mysql query throw an error, for example if a row does not exist. The node server crashes.
connection.connect();
connection.query('SELECT * from table1 where id = 2', function(err, rows, fields) {
if (err) console.log(err);
if (rows[0]) {
console.log('The result is ', rows[0].user);
}
});
connection.end();
How do I simply print the errors to the page rather than crash the server.
If an error occurs, your code console.log's it but tries to access rows[0] anyway. In case of errors rows will be undefined so rows[0] will trigger a new error.
Easily fixed with an else in combination with a length check:
if (err) {
console.log(err);
} else if (rows.length) {
console.log('The result is ', rows[0].user);
} else {
console.log("Query didn't return any results.");
}
I prefer to use the return statement:
connection.connect();
connection.query('SELECT * from table1 where id = 2', function(err, rows, fields) {
if (err) return console.log(err);
if (rows[0]) {
console.log('The result is ', rows[0].user);
}
});
connection.end();
This is cleaner IMO and guarantees that I wont leave anything out of an if statement block where it shouldn't.