SQL Injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve.
This might include data belonging to other users, or any other data that the application itself is able to access. In many cases, SQL Injection can allow an attacker to modify or delete this data, causing persistent changes to the applicationโs content or behavior.
Example of a vulnerable query:
SELECT * FROM users WHERE email = 'user@example.com';
If the input is not sanitized, a malicious user might enter this as email:
' OR '1'='1
This would change the query to:
SELECT * FROM users WHERE email = '' OR '1'='1';
Which returns all users, bypassing login restrictions.
To prevent SQL Injection, always use parameterized queries or prepared statements. Hereโs an example using a secure method:
const userEmail = req.body.email;
const query = 'SELECT * FROM users WHERE email = ?';
connection.query(query, [userEmail], function(err, results) {
// safe query execution
});
Always validate and sanitize inputs and avoid directly inserting user input into SQL strings.