DEV Community

Cover image for SQL Injection
Moses Ikechukwu
Moses Ikechukwu

Posted on

SQL Injection

What is SQL Injection?

SQL Injection (SQLi) is a web security vulnerability that allows attackers to manipulate a website’s database by injecting malicious SQL code into input fields. It can lead to unauthorized access, data theft, modification, or even complete deletion of a database.

How SQL Injection Works

When a web application improperly handles user input, an attacker can insert SQL commands into a query. For example, consider this vulnerable PHP code:

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);

If an attacker enters admin' -- as the username, the query becomes:

SELECT * FROM users WHERE username = 'admin' --' AND password = ''

The -- comment operator ignores the rest of the statement, bypassing authentication.

Consequences of SQL Injection

Unauthorized Access – Attackers can log in as admin without credentials.

Data Theft – Sensitive user information, including passwords, can be exposed.

Data Manipulation – Hackers can modify or delete database records.

System Compromise – In severe cases, an attacker can gain full control of the server.

Preventing SQL Injection

  1. Use Prepared Statements and Parameterized Queries:

$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();

  1. Sanitize User Input – Use htmlspecialchars() to prevent special character interpretation.

  2. Use Least Privilege Principle – Restrict database user permissions.

  3. Employ Web Application Firewalls (WAF) – Detect and block SQL injection attempts.

Conclusion

SQL Injection is one of the most dangerous web vulnerabilities but can be prevented with secure coding practices. By using parameterized queries, input validation, and proper access control, developers can protect applications from SQLi attacks.

Top comments (0)