SQL injection (SQLi) is a simple yet dangerous vulnerability.

Itβs simple because itβs easily preventable.
Itβs dangerous because your data will be stolen, your database will be dropped, and your job will be lost.
Any app that uses a SQL database, which is the majority of them, could be vulnerable to it.
SQLi
To interact with a SQL database, you write queries.

Many of them arenβt fixed.
They depend on user inputs.
For example, this query depends on two variables: username and password.

They are user inputs that usually come from the frontend.
Like a login page.
A flow typical flow is:
User fills in the form

Frontend sends that data to the backend

Backend creates a SQL query

Okay. What if we put something weird in the form?
Like an extra quote after the password (1234β):

A syntax error occurs.

So we can change the SQL query with our input.
How can we exploit that?
If you put something like this in the form.

It will create a query that always returns true:

You can now log in to anyoneβs account without knowing their password.

Preventing SQLi
To prevent the vulnerability, you need to know what went wrong.
Usually, SQLi occurs when the developer creates a raw SQL query using string concatenation, like this:
const query = "SELECT * FROM USERS " +
"WHERE username = '" + username + "' " +
"AND password = '" + password + "'";Or this:
const query = `SELECT * FROM USERS
WHERE username = ${username}
AND password = ${password}`Bad idea. Instead, use a prepared statement.
A prepared statement is like a function parameter.
You pass arguments into the SQL query when itβs run, which looks like this:

By doing that, the database will be able to interpret the values as literal data rather than SQL code.
Fee from Anime Coders
