nodejs throws error with mysql like query via prepared statements - mysql

Am retrieving values from database using nodejs.
I implemented mysql like query via prepared statement to ensure that sql injection attack is eliminated. my problem is that it does not retrieve any result. it just show empty results in the console please can someone point to me what is wrong with the query
exports.autosearch = function (req, res) {
//var search = req.body.searchText;
var search = 'bukatti';
//db.query('SELECT * FROM users WHERE name like ?', ['%' + search + '%'], function (error, results, fields) {
db.query('SELECT * FROM users WHERE name like ?', ['%search%'], function (error, results, fields) {
console.log(results);
});
}
Thanks

I have found out my problem. i added the error log and discover that the was type error somewhere. This fix it anyway
db.query("SELECT * FROM users WHERE name like ?", ['%' + search + '%'], function (error, results, fields) {
Thanks

Related

Node.JS - SQL Injection in URL parameters?

I'm trying to learn Node.js and I'm currently making an Express app (using ejs) that will return values from a MySQL database, depending on the URL the user visits.
For example, visiting http://localhost:3000/test will list all users from the db table users. And the link http://localhost:3000/test/3 will return information about the user with the id number 3.
My code for: /test
app.get("/test", (req, res) => {
let sql = "SELECT * FROM users ORDER BY name";
db.query(sql, function (err, results, fields) {
if (err)
logmessage(err.message);
res.render("test", { data: results });
});
});
And here is the code for /test/:id
app.get("/test/:id", (req, res) => {
var userId = req.params.id;
let sql = "SELECT * FROM users WHERE id = " + userId;
db.query(sql, function (err, results, fields) {
if (err || !results.length) {
res.redirect("/");
} else {
res.render("test_user", { data: results });
}
});
});
My question is: is this safe? When I previously worked in PHP development, I used to prepare statements before making any queries.
What happens if a user changes the URL from: http://localhost:3000/test/3 and inserts some SQL injection code at the end of the url? Can the database be breached?
This will be for a live app on the web, so it's important no SQL injection can be made. I also want to add a form later on (req.body instead of req.params) that I also need to sanitize.
Or is there a built-in "prepared statement" already in Node?
SQL injection is prevented if you use placeholders:
let sql = "SELECT * FROM users WHERE id = ?";
db.query(sql, [userId], function (err, results, fields) {...});
Have you tried to implement Sequelize? From what I read ORMs prevent SQL injection. Also, it's pretty easy to use :)

Preventing Nodejs MySQL SQL Injection

How do I prevent SQL injection for NodeJS? I am trying to prevent SQL Injection using the ? symbol and the req.param. But I am not able to get to work. How should I use the req.param.id correctly? Many thanks in advance.
app.get('/products/:id', (req, res) => {
conn.getConnection(function (err, connection) {
if (err) throw err;
const SELECT_WHERE_PRODUCT_ID_QUERY = `SELECT * FROM products WHERE id = ?, $[req.param.id]`
connection.query(SELECT_WHERE_PRODUCT_ID_QUERY, function (error, results, fields) {
connection.release()
if (error) throw error;
return res.send(results)
});
});
});
Yes, we should use prepared statements for that and ? as placeholders. In order to make it work, we should pass parameters as a separate argument:
const query = 'SELECT * FROM products WHERE id = ?';
const params = [req.param.id];
connection.query(query, params, function (error, results, fields) {
Another form:
connection.query(
{
sql: 'SELECT * FROM products WHERE id = ?',
values: [req.param.id]
},
function (error, results, fields) {
See documentation for more examples.
This should prevent SQL injection.
const SELECT_ALL_PRODUCT_QUERY = 'SELECT * FROM products WHERE id = ?'
connection.query(SELECT_ALL_PRODUCT_QUERY,[req.params.id], function (error, results)

MySQL query works with POST but not with GET (Node/Express)

POST works but GET doesn't work.
This works:
app.post('/POSTexample', function(req, res) {
connection.query('SELECT * FROM users WHERE username = ?', req.session.username, function(error, results, fields) {
#using query results
response.redirect('/account');
});
res.redirect('/account');
});
But this doesn't work (gets stuck and never loads):
app.get('/GETexample', function(req, res) {
connection.query('SELECT * FROM users WHERE username = ?', req.session.username, function(error, results, fields) {
#using query results
});
res.redirect('/account');
});
What are the possible solutions to this issue?
Put your res.redirect() calls in the callback function from your MySql queries. The way you have it, you're redirecting before the queries complete.
asynchronous coding takes some getting used to, doesn't it?

Node Express MySQL multiple routing

I want to make an route with multiple parameters using Node Express MySQL. Is it possible to do this with traditional url parameters like: page?id=2&user=10
Here is a simple query, but the only way of doing it so far is like this: page/2/10
app.get("/get-page/:id/:user", function (req, res) {
let sql = "SELECT * FROM table WHERE id= '${req.params.id}' AND userid= '${req.params.user}'`;";
let query = db.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
});
This is just an example.
The reason I would like the traditional way is because, with the "slash" method the parameters always have to come in the correct order, or did I miss something?
Perhaps use the query property of the request to access the query string, as in req.query.id:
app.get("/get-page", function (req, res) {
console.log('ID: ' + req.query.id)
});

Variable in MySQL Query causes error

I have a node.js app using node-mysql to query a MySQL database.
Problem: It appears that when I make the table name in the query a variable, things stop working. Did I miss out on something?
Working Node Code
client.query('SELECT * from tableA',
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
Non-working Node Code
client.query('SELECT * from ?',
[ tableA ],
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
You could probably just append the table name to the string (pseudo code, I don't know node.js)
client.query('SELECT * from ' + [tablaA],
function(error, results, fields) {
if (error)
throw error;
callback(results);
});
They reason why it's not working is pretty clear.
The query from the non-working code will be :
SELECT * from 'tableA'
A solution is the one from #Andreas, but you will have the same problem in a where statement or insert for other values you don't want to be escaped like "null" value. ( convert into a string)
Same problem here
Check out the source how format && escape from node-mysql works.