0
0
PhpDebug / FixBeginner · 4 min read

How to Prevent SQL Injection in PHP: Secure Your Database

To prevent SQL injection in PHP, always use prepared statements with parameterized queries instead of inserting user input directly into SQL strings. This ensures user data is treated safely and not executed as SQL code.
🔍

Why This Happens

SQL injection happens when user input is directly added to SQL queries without checks. Attackers can insert harmful SQL code that changes the query's meaning, leading to data leaks or damage.

php
<?php
$user_input = "' OR '1'='1";
$sql = "SELECT * FROM users WHERE username = '$user_input'";
// This query becomes: SELECT * FROM users WHERE username = '' OR '1'='1'
// which returns all users, bypassing login checks
Output
Query returns all users, bypassing intended restrictions.
🔧

The Fix

Use prepared statements with parameterized queries to separate SQL code from user data. This way, the database treats user input only as data, not code, preventing injection.

php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$user_input = "' OR '1'='1";
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute([':username' => $user_input]);
$results = $stmt->fetchAll();
print_r($results);
Output
Array ( ) // No users returned because input is treated safely
🛡️

Prevention

Always use prepared statements with parameter binding for all database queries involving user input. Avoid building SQL queries by concatenating strings. Use PDO or MySQLi with prepared statements. Validate and sanitize inputs as an extra safety layer. Enable error reporting during development to catch issues early.

⚠️

Related Errors

Other common errors include using deprecated mysql_* functions, which do not support prepared statements, and trusting client-side validation only. Also, forgetting to handle exceptions can hide SQL errors.

Key Takeaways

Always use prepared statements with parameterized queries to prevent SQL injection.
Never insert user input directly into SQL query strings.
Use PDO or MySQLi extensions that support prepared statements.
Validate and sanitize user inputs as an additional safety measure.
Enable error reporting during development to detect issues early.