0

I am trying to make my sql statements more secure for an API that I am developing. While I know that there are ORM tools that make this easier, I am new at this and want to understand the basics, and best practices. I first created an sql statement that concatenated the values into a string. It was recommended in a previous post of mine that it would leave me vulnerable to SQL injections. I tried the recommended approach but was not successful. The question mark used as a placeholder was never replaced with the value i was trying to pass it.

Note: although related, it is not a duplicate of [Passing a node.js parameter in sql query. The usage and solutions are slightly different.

Any help would be greatly appreciated!

I have tried several ways but each time the ? was never replaced. I can see this in the console. I also logged the value of 'id' to make sure that there was a value to be passed at that level in the functions scope.

Note: this originated from the following issue: How do I insert a value into a select statement using JavaScript, specifically when using express and postgres?

This works but is not very safe...

    return db.query(`SELECT * FROM users WHERE id = ${id}`);

None of the following worked...

return db.query('SELECT * FROM `users` WHERE `id` = ?',['id']);
return db.query('SELECT * FROM users WHERE id = ?',['id']);
return db.query('SELECT * FROM users WHERE id = ?',[id]);
return db.query('SELECT * FROM users WHERE id = ?',id);
return db.query(`SELECT * FROM users WHERE id = ?`,id);

Each time the console shows the following...

QUERY:  SELECT * FROM users WHERE id = ?
5
  • Possible duplicate of Passing a node.js parameter in sql query Commented Sep 8, 2019 at 20:54
  • Link the official documentation for db.js Commented Sep 8, 2019 at 21:02
  • 1
    The docs say you need to use $1, $2 etc Commented Sep 8, 2019 at 21:09
  • @ChrisG thanks! This resolved my issue. Commented Sep 9, 2019 at 12:55
  • Note: although related, it is not a duplicate of [stackoverflow.com/questions/47538998/…. The usage and solutions are slightly different. Commented Sep 9, 2019 at 12:57

1 Answer 1

0

Usign $ as a placeholder rather than a questionmark with Node.js worked.

Example:

return db.query('SELECT * FROM users WHERE id = $1',[id]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.