How to fix SQL injection vulnerabilities in PHP?


By Faraz - June 10, 2023

Learn effective techniques to safeguard your PHP code against SQL injection attacks.

To prevent SQL injection in PHP, you should use prepared statements or parameterized queries instead of directly interpolating user input into your SQL queries. Prepared statements separate the SQL code from the user input, making it impossible for malicious input to alter the structure of your query.

Here's an example of how you can use prepared statements in PHP with MySQLi:

// Establish a database connection
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Prepare a SQL statement with a placeholder
$stmt = $mysqli->prepare('SELECT * FROM users WHERE username = ?');

// Bind user input to the placeholder
$username = $_POST['username'];
$stmt->bind_param('s', $username);

// Execute the prepared statement

// Get the results
$result = $stmt->get_result();

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Do something with the data
    echo $row['username'];

// Close the statement and database connection

In this example, the ? is used as a placeholder for the user input in the SQL query. The bind_param method binds the user input to the placeholder, ensuring it is treated as a parameter and not part of the SQL statement. This prevents any possibility of SQL injection.

It's important to note that using prepared statements alone is not enough. You should also validate and sanitize user input before using it in the query. This helps ensure that only expected data is passed into the query. Additionally, you should avoid dynamically constructing SQL queries using user input or any unsanitized data.

Here are some other best practices to follow:

1. Use Prepared Statements (Parameterized Queries): Instead of embedding user input directly into SQL statements, use prepared statements with placeholders. Prepared statements separate the SQL logic from the data, preventing SQL injection attacks.

Example using PDO:

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);

Example using MySQLi:

$stmt = $mysqli->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);

2. Sanitize User Input: Even when using prepared statements, it's essential to sanitize user input to remove any unwanted characters. Use functions like filter_var() or mysqli_real_escape_string() to sanitize user input.


$username = mysqli_real_escape_string($connection, $_POST['username']);

3. Limit Database User Privileges: Ensure that the database user account used by your PHP application has the least privileges required to perform its tasks. Avoid using a privileged account with full administrative access.

4. Implement Input Validation: Validate user input on the server-side to ensure it conforms to the expected format and type. This step helps prevent not only SQL injection but also other forms of attacks or errors.


if (ctype_alnum($username)) {
    // Proceed with the query
} else {
    // Handle invalid input

5. Avoid Dynamic SQL Queries: Minimize the use of dynamic SQL queries where user input is directly concatenated into the query. Instead, use prepared statements and bind variables to ensure proper data separation.

6. Update PHP and Database Versions: Keep your PHP version and database software up to date with the latest security patches and fixes. Newer versions often include security improvements and bug fixes that can help mitigate vulnerabilities.

7. Use Web Application Firewalls (WAFs): Implement a web application firewall to provide an additional layer of protection against common attacks, including SQL injection. WAFs can help detect and block malicious traffic targeting your application.

By following these practices, you can significantly reduce the risk of SQL injection vulnerabilities in your PHP application. Remember that security is an ongoing process, and it's crucial to stay updated on the latest security best practices and emerging threats.

I hope you found the above information helpful. Please let me know in the comment box if you have an alternate answer πŸ”₯ and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox

Related Post