← Back to all snippets
PHP

Prevent SQL Injection with PHP PDO Prepared Statements

Secure your database queries from SQL injection attacks using PHP Data Objects (PDO) with prepared statements and parameterized queries for safe data handling.

<?php
$host = 'localhost';
$db   = 'your_database';
$user = 'your_user';
$pass = 'your_password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false, // Crucial for security
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
    echo "Successfully connected to the database.
";

    // --- Example 1: SELECT query with user input ---
    $userId = 1; // User-provided ID, e.g., from $_GET['id']
    // $userId = "1 OR 1=1"; // Example of malicious input if not using prepared statements

    $stmt = $pdo->prepare("SELECT name, email FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
    $stmt->execute();

    $user = $stmt->fetch();
    if ($user) {
        echo "User found: Name - " . $user['name'] . ", Email - " . $user['email'] . "
";
    } else {
        echo "User with ID $userId not found.
";
    }

    // --- Example 2: INSERT query with user input ---
    $newName = "Jane Doe";
    $newEmail = "[email protected]";
    $newPasswordHash = '$2y$10$abc...'; // Hashed password from password_hash()

    $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash) VALUES (:name, :email, :password_hash)");
    $stmt->bindParam(':name', $newName);
    $stmt->bindParam(':email', $newEmail);
    $stmt->bindParam(':password_hash', $newPasswordHash);
    $stmt->execute();

    echo "New user '{$newName}' inserted with ID: " . $pdo->lastInsertId() . "
";

} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
How it works: This PHP snippet demonstrates the crucial practice of preventing SQL injection attacks using PDO (PHP Data Objects) with prepared statements. Instead of directly embedding user input into the SQL query string, prepared statements separate the SQL logic from the data. Placeholders (like `:id`, `:name`) are used in the query, and user-provided values are then bound to these placeholders *before* the query is executed. This ensures that any special characters in the input are treated purely as data, not as executable SQL code. `PDO::ATTR_EMULATE_PREPARES => false` is important for ensuring the database itself handles the preparation, offering stronger security.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs