How to Prevent SQL Injection in PHP: Secure Your Database
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 $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
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 $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);
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.