Learn how to write secure PHP code that protects your database from SQL injection attacks using PDO and prepared statements.
๐ก๏ธ What is SQL Injection?
SQL injection is a common attack where malicious users insert SQL code into your application's input fields to access, manipulate, or delete database information. It can lead to severe data breaches and is one of the most dangerous web security risks.
โ Insecure Query Example
This code is vulnerable to SQL injection:
<?php $username = $_GET['username']; $query = "SELECT * FROM users WHERE username = '$username'"; $result = mysqli_query($conn, $query); ?> If a user inputs admin' OR '1'='1, it can return all users in the table!
โ Using PDO with Prepared Statements
Prepared statements separate the SQL logic from user input, making injections nearly impossible.
๐ Step-by-step:
<?php $pdo = new PDO("mysql:host=localhost;dbname=demo", "user", "pass"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $username = $_GET['username']; $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username"); $stmt->execute(['username' => $username]); $user = $stmt->fetch(); ?> The :username placeholder is replaced securely by PDO with the actual value.
๐ Insert with Prepared Statement
<?php $stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)"); $stmt->execute([ 'username' => 'newuser', 'email' => '[email protected]' ]); ?> This ensures all data is escaped and safe before hitting the database.
๐ Best Practices
- Always use prepared statements , never insert raw user input directly into SQL queries
- Validate and sanitize input even when using PDO
- Use named parameters (
:param) for clarity and flexibility - Never use dynamic SQL unless absolutely necessary , and even then, parameterize it
๐งพ Summary
Preventing SQL injection is essential for secure PHP applications. By using PDO and prepared statements, you ensure that user data is safely separated from SQL logic. Combined with proper input validation, your app will be well-protected against one of the webโs most dangerous vulnerabilities.