How can I prevent SQL injection in PHP?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
In the example above, if an attacker submits ' OR 1=1 --, the query becomes:
This effectively bypasses the password check and logs the attacker in as the first user in the users' table.
Techniques to Prevent SQL Injection
1. Use Prepared Statements
Prepared statements ensure that user input is treated strictly as data and not executable code.
Example:
2. Use PDO (PHP Data Objects)
PDO is a database access layer that provides a uniform method of access to multiple databases. It automatically helps prevent SQL injection through prepared statements.
Example:
3. Input Validation
Always validate and sanitize user input. Ensure data types are consistent with the expected input.
Example:
4. Escape User Input
If using raw SQL queries, always escape user inputs. This is a less preferred method but can be used with good sanitation practices.
Example with mysqli real escape function:
Summarizing Key Prevention Techniques
| Technique | Example Code Snippet/Explanation |
| Use Prepared Statements | $stmt = $conn->prepare("SELECT ... WHERE username = ?"); |
| Use PDO | $stmt = $pdo->prepare("SELECT ... WHERE username = :username"); |
| Input Validation | $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); |
| Escape User Input | $username = $conn->real_escape_string($_POST['username']); |
Additional Considerations
Use of Stored Procedures
Stored procedures are precompiled SQL queries. Use them to encapsulate the logic within the database, reducing reliance on client-side constructs.
Least Privilege Principle
Ensure database users have the minimal privileges necessary for the tasks they need to perform. For instance, avoid using an account with DROP or DELETE privileges for read-only operations.
Regular Security Audits
Regularly review and test your code for SQL injection vulnerabilities. Use automated tools and conduct code reviews to identify potential vulnerabilities.
Secure Configuration
Always keep your PHP and database server configurations secure and up-to-date with the latest security patches. Disable any functions and features that are not needed.
Preventing SQL injection is all about securing all entry points to your application where SQL queries are performed. Using the techniques outlined above, developers can build more secure applications that are robust against SQL injection attacks.

