Languages
[Edit]
EN

Node.js - MySQL - how to prevent SQL injection

6 points
Created by:
Kia-H
546

In this article, we would like to show you how to prevent SQL injection in MySQL

SQL injection is a serious problem for web developers. It involves entering a SQL subquery in place of the main query value, which may then be incorrectly processed by the database.

Below we present 3 ways to defend against SQL injection Attack:

In each case, we will try to pass the 'SELECT * FROM `users` WHERE `salary` < 3700' query.

Note: At the end of this article, you'll find some database preparation files that you can practice on.

1. escape() method

Edit

The first way is to use connection.escape() method, which arguments are a value we are getting from the user, so the one that could turn out to be unsafe.
Next step is to pass the query to the method which sends the query to the database.

2. Placeholders

Edit

In this case, we create a query that has question marks in the places where we want to insert something. values in the array are inserted in the order in which they were passed.

Note: ? is for ordinary values, ?? is used for column and table names.

3. named-placeholders

Edit

The last way is to use the external npm package - named-placeholders. It is similar to the previous method, but in this case, we have more control over the order and what will be passed.

Note: :x is for ordinary values, ::x is used for column and table names.

Database preparation

Edit

create_tables.sql file:

insert_data.sql file:

References

  1. SQL injection - wikipedia
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - MySQL

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join