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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay