codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐘

PHP

41 / 56 topics
40Security in PHP41Preventing SQL Injection42Cross-Site Scripting (XSS)
Tutorials/PHP/Preventing SQL Injection
🐘PHP

Preventing SQL Injection

Updated 2026-04-20
2 min read

Introduction

SQL injection is one of the most common and critical security vulnerabilities in web applications that interact with databases. It occurs when an attacker manipulates a SQL query by injecting malicious SQL code through user input fields such as forms, URL parameters, or cookies. This can lead to unauthorized access to sensitive data, data manipulation, or even complete database compromise.

In this tutorial, we will explore how to prevent SQL injection in PHP applications using best practices and secure coding techniques. We'll cover various methods including prepared statements, parameterized queries, input validation, and error handling.

Understanding SQL Injection

Before diving into prevention techniques, it's essential to understand how SQL injection works. Here’s a simple example to illustrate the vulnerability:

// Vulnerable code
$username = $_GET['username'];
$password = $_GET['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($connection, $query);

if (mysqli_num_rows($result) > 0) {
    echo "Login successful!";
} else {
    echo "Invalid credentials.";
}

In this example, if an attacker inputs admin' -- as the username and any value for the password, the SQL query becomes:

SELECT * FROM users WHERE username='admin' --' AND password='any_value'

The -- comment out the rest of the query, effectively bypassing the password check.

Preventing SQL Injection

1. Use Prepared Statements and Parameterized Queries

Prepared statements are a powerful feature in PHP that helps prevent SQL injection by separating SQL logic from data. They ensure that user input is treated as data rather than executable code.

Using PDO (PHP Data Objects)

PDO provides a consistent interface for accessing databases, supporting multiple drivers like MySQL, PostgreSQL, and SQLite.

// Using PDO with prepared statements
try {
    $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username=:username AND password=:password");
    $stmt->execute([':username' => $_GET['username'], ':password' => $_GET['password']]);
    
    if ($stmt->rowCount() > 0) {
        echo "Login successful!";
    } else {
        echo "Invalid credentials.";
    }
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

Using MySQLi

MySQLi is another option for database interaction in PHP, offering similar functionality to PDO.

// Using MySQLi with prepared statements
$mysqli = new mysqli('localhost', 'username', 'password', 'testdb');

if ($stmt = $mysqli->prepare("SELECT * FROM users WHERE username=? AND password=?")) {
    $stmt->bind_param("ss", $_GET['username'], $_GET['password']);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        echo "Login successful!";
    } else {
        echo "Invalid credentials.";
    }
    
    $stmt->close();
}
$mysqli->close();

2. Input Validation and Sanitization

Even with prepared statements, it's important to validate and sanitize user inputs to ensure they meet expected formats and constraints.

// Input validation example
function validateInput($input) {
    // Remove any illegal characters from the input
    $cleanedInput = filter_var($input, FILTER_SANITIZE_STRING);
    
    // Check if the cleaned input is empty or too long
    if (empty($cleanedInput) || strlen($cleanedInput) > 255) {
        throw new Exception("Invalid input.");
    }
    
    return $cleanedInput;
}

try {
    $username = validateInput($_GET['username']);
    $password = validateInput($_GET['password']);
    
    // Proceed with prepared statements as shown earlier
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

3. Error Handling and Logging

Proper error handling is crucial to prevent attackers from gaining insights into your database structure or application logic.

// Improved error handling with PDO
try {
    // Database connection and query execution code here
} catch (PDOException $e) {
    // Log the error message securely
    error_log("Database error: " . $e->getMessage());
    
    // Display a generic error message to the user
    echo "An error occurred while processing your request.";
}

4. Least Privilege Principle

Ensure that database users have only the necessary permissions required for their tasks. For example, if an application only needs to read data, grant it read-only access.

-- Example SQL command to create a user with limited privileges
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT ON testdb.* TO 'app_user'@'localhost';
FLUSH PRIVILEGES;

5. Use ORM (Object-Relational Mapping) Libraries

ORM libraries like Eloquent (Laravel), Doctrine, or Propel abstract database interactions and provide built-in protection against SQL injection.

// Using Eloquent ORM example
use App\Models\User;

try {
    $user = User::where('username', $_GET['username'])
               ->where('password', $_GET['password'])
               ->first();
    
    if ($user) {
        echo "Login successful!";
    } else {
        echo "Invalid credentials.";
    }
} catch (\Exception $e) {
    error_log("Database error: " . $e->getMessage());
    echo "An error occurred while processing your request.";
}

Conclusion

Preventing SQL injection is a critical aspect of securing PHP applications. By using prepared statements, validating and sanitizing inputs, implementing robust error handling, adhering to the least privilege principle, and leveraging ORM libraries, you can significantly reduce the risk of SQL injection attacks.

Always stay updated with the latest security practices and regularly review your code for potential vulnerabilities. Remember that security is an ongoing process, and continuous improvement is essential in protecting your applications from evolving threats.


PreviousSecurity in PHPNext Cross-Site Scripting (XSS)

Recommended Gear

Security in PHPCross-Site Scripting (XSS)