SQL Injection in PHP: How to Prevent It with PDO and Prepared Statements

Illustration of SQL injection protection in PHP

Quick answer: SQL injection happens when text sent by the user is concatenated straight into an SQL query. To prevent it, use PDO with prepared statements: write the SQL with placeholders (:email or ?) and pass the values to execute(), so they are never interpreted as SQL. Configure PDO with ERRMODE_EXCEPTION and EMULATE_PREPARES turned off, and apply this to logins, searches, INSERT, UPDATE and DELETE.

SQL injection is one of the best-known security flaws in web applications. It happens when user input is placed directly inside an SQL query without proper handling. In PHP it often shows up in login systems, search forms, sign-up forms, filters, APIs and admin panels.

The good news is that preventing SQL injection in PHP is not complicated when you use PDO with prepared statements. The values sent by the user are treated as parameters, never as part of the SQL command.

In this article you will see what SQL injection is, look at vulnerable code and learn how to fix it with PDO, named parameters, input validation and good practices.

In short: never build SQL by concatenating values from $_GET, $_POST, JSON or any other external input. Use PDO with prepared statements.

What is SQL injection?

SQL injection is a way of manipulating SQL queries through data sent by the user. When an application builds a query by mixing SQL text with external values without protection, an attacker can change what the query does.

Instead of sending just an email address, a name or an ID, the attacker sends a piece of malicious SQL. If the code concatenates that value into the query, the database runs it as part of the command.

That can lead to:

  • Unauthorized access to accounts;
  • Private data being listed;
  • Records being changed or deleted;
  • Login bypass;
  • Leaks of sensitive information;
  • The whole application being compromised.

Example of vulnerable PHP code

Here is a common example of vulnerable code on a login screen:

<?php

$email = $_POST['email'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";

$result = $pdo->query($sql);
$user = $result->fetch();

This code is dangerous because $email and $password go straight into the query. If someone sends ' OR '1'='1 in the email field, the condition is always true and the query returns the first user, often the administrator. (It also stores passwords in plain text, which is a second problem we fix below.)

Watch out: even if the frontend validates the form with JavaScript, the backend still has to protect the query. Anyone can call your API or form directly.

Why is concatenating SQL dangerous?

When you concatenate, the database can't tell which part is SQL and which part is a value sent by the user.

Bad example:

<?php

$id = $_GET['id'];

$sql = "SELECT * FROM users WHERE id = $id";

If $id arrives as 10, the query works. If it arrives as 10 OR 1=1, the query returns every user. External data must never go directly into the SQL string.

The right way: PDO with prepared statements

Prepare the query first and send the values separately:

<?php

$id = $_GET['id'];

$sql = "SELECT * FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);

$stmt->execute([
    ':id' => $id
]);

$user = $stmt->fetch();

Here :id is a named parameter, and the real value is sent separately in execute. The value is never interpreted as part of the SQL command.

Creating a secure PDO connection

Before using prepared statements, create the PDO connection with good settings:

<?php

try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
        'user',
        'password',
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );
} catch (PDOException $e) {
    error_log('Connection error: ' . $e->getMessage());

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error.'
    ]);
    exit;
}

PDO::ATTR_EMULATE_PREPARES => false makes PDO use real prepared statements when the driver supports them. Setting charset=utf8mb4 in the DSN also matters: it avoids old charset tricks that could break escaping.

One side effect of native prepares in MySQL: each named placeholder can appear only once per query. If you need the same value twice, use two placeholders (for example :search1 and :search2), as in the examples below. Otherwise you get SQLSTATE[HY093]: Invalid parameter number.

Safe example: find by ID

To find a user by ID, validate the parameter and use bindValue:

<?php

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id <= 0) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid ID.'
    ]);
    exit;
}

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

$user = $stmt->fetch();

if (!$user) {
    http_response_code(404);
    echo json_encode([
        'success' => false,
        'message' => 'User not found.'
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'data' => $user
]);

There are two layers of protection here: the ID is validated, and the query is prepared.

Safe example: login with PHP and PDO

In a login system, besides preventing SQL injection, never compare passwords in plain text. Store them with password_hash and check them with password_verify.

<?php

$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = $_POST['password'] ?? '';

if ($email === '' || $password === '') {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Email and password are required.'
    ]);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Enter a valid email address.'
    ]);
    exit;
}

$sql = "SELECT id, name, email, password_hash FROM users WHERE email = :email LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':email' => $email
]);

$user = $stmt->fetch();

if (!$user || !password_verify($password, $user['password_hash'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid email or password.'
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'message' => 'Logged in.',
    'data' => [
        'id' => $user['id'],
        'name' => $user['name'],
        'email' => $user['email']
    ]
]);

Notice that the password never goes into the query. First we look the user up safely by email, then we check the password with password_verify. The error message is the same whether the email or the password is wrong, so attackers can't find out which emails exist.

Safe example: INSERT

<?php

$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = $_POST['password'] ?? '';

if ($name === '' || $email === '' || $password === '') {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Fill in all required fields.'
    ]);
    exit;
}

$passwordHash = password_hash($password, PASSWORD_DEFAULT);

$sql = "INSERT INTO users (name, email, password_hash) VALUES (:name, :email, :password_hash)";
$stmt = $pdo->prepare($sql);

$stmt->execute([
    ':name' => $name,
    ':email' => $email,
    ':password_hash' => $passwordHash
]);

echo json_encode([
    'success' => true,
    'message' => 'User created.',
    'data' => [
        'id' => $pdo->lastInsertId()
    ]
]);

Even in an INSERT, external data is still sent as parameters.

Safe example: UPDATE

<?php

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';

if ($id <= 0) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid ID.'
    ]);
    exit;
}

$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);

$stmt->bindValue(':name', $name);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);

$stmt->execute();

echo json_encode([
    'success' => true,
    'message' => 'User updated.'
]);

The id is cast to an integer and the other fields are passed as parameters. In a real API, also check that the logged-in user is allowed to edit this record.

Safe example: DELETE

<?php

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

if ($id <= 0) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Invalid ID.'
    ]);
    exit;
}

$sql = "DELETE FROM users WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([
    'success' => true,
    'message' => 'User deleted.'
]);

In real systems, a soft delete (a deleted_at or active column) is often better than deleting the row for good.

LIKE searches with prepared statements

A common myth is that LIKE can't be used with prepared statements. It can, as long as the wildcards go into the parameter value:

<?php

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$term = '%' . $search . '%';

$sql = "SELECT id, name, email FROM users WHERE name LIKE :search1 OR email LIKE :search2";
$stmt = $pdo->prepare($sql);

$stmt->execute([
    ':search1' => $term,
    ':search2' => $term
]);

$results = $stmt->fetchAll();

echo json_encode([
    'success' => true,
    'data' => $results
]);

The value with % is passed as a parameter, not concatenated into the query. Note the two placeholders for the same value, needed with native prepares.

Filters with multiple parameters

In APIs with filters you can build the conditions dynamically, as long as the values stay parameterized:

<?php

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = "status = :status";
    $params[':status'] = $status;
}

if ($search !== '') {
    $where[] = "(name LIKE :search1 OR email LIKE :search2)";
    $params[':search1'] = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = 'WHERE ' . implode(' AND ', $where);
}

$sql = "SELECT id, name, email, status FROM users {$whereSql} ORDER BY id DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

$users = $stmt->fetchAll();

Only fixed pieces of SQL written by you go into $where; every user value goes into $params. This pattern works for filters by status, category, date, user or type.

Be careful with a dynamic ORDER BY

Column names and sort directions can't be passed as parameters the way values can. Use an allowlist:

<?php

$orderBy = $_GET['order_by'] ?? 'id';
$orderDir = strtolower($_GET['order_dir'] ?? 'desc');

$allowedColumns = ['id', 'name', 'email', 'created_at'];
$allowedDirections = ['asc', 'desc'];

if (!in_array($orderBy, $allowedColumns, true)) {
    $orderBy = 'id';
}

if (!in_array($orderDir, $allowedDirections, true)) {
    $orderDir = 'desc';
}

$sql = "SELECT id, name, email FROM users ORDER BY {$orderBy} {$orderDir}";

Because order_by and order_dir become part of the query's structure, they must be limited to known values. The same applies to table names and LIMIT values (cast those to integers).

Does addslashes prevent SQL injection?

Not reliably. addslashes and other manual escaping don't replace prepared statements: they can fail depending on the database, charset, driver and query context. With properly configured PDO, the SQL command and the values travel separately.

Rule of thumb: don't build your own SQL injection protection with string replacements. Use prepared statements.

Input validation still matters

Prepared statements protect the query, but they don't replace validation. You still need to check that values make sense:

  • An ID must be a positive integer;
  • An email must have a valid format;
  • A password must have a minimum length;
  • A status must be in an allowed list;
  • Dates must have the correct format;
  • Required fields can't be empty.

Good security combines prepared statements, validation, access control and error handling.

Never show SQL errors to users

In production, database error messages should never appear in an API response or on screen. Avoid returning something like:

SQLSTATE[42S22]: Column not found: 1054 Unknown column...

That kind of message reveals internal details of your application. Log the error and return a generic message:

<?php

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
} catch (PDOException $e) {
    error_log('SQL error: ' . $e->getMessage());

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Internal server error.'
    ]);
    exit;
}

If you are chasing a 500 error, see how to find the cause of a PHP 500 error in the logs.

Checklist to prevent SQL injection in PHP

  • Never concatenate external values into SQL;
  • Use PDO with prepared statements;
  • Use named or positional parameters;
  • Validate IDs as integers;
  • Validate emails, dates, statuses and required fields;
  • Use an allowlist for ORDER BY columns;
  • Don't rely on addslashes;
  • Never show SQL errors to end users;
  • Log failures;
  • Use password_hash and password_verify for logins;
  • Limit the database user's privileges;
  • Keep PHP, the database and dependencies up to date.

The database user's privileges matter too

Besides protecting the code, give the application's database user only the privileges it needs. If an application only reads and writes rows, it doesn't need permission to drop tables. Fewer privileges limit the damage if something does go wrong.

Common mistakes when trying to prevent SQL injection

1. Thinking frontend validation is enough

The frontend is easy to bypass. Protection has to be on the backend.

2. Concatenating "because it's just an ID"

IDs must also be validated and sent as parameters.

3. Using addslashes as the main protection

Manual escaping is not as safe as prepared statements.

4. Parameterizing values but not validating ORDER BY

Sort columns and directions must go through an allowlist.

5. Showing the real database error in production

Internal messages belong in the logs, not in the public response.

Complete example of a protected endpoint

A complete endpoint that lists users with search, status filter, safe sorting and prepared statements:

<?php

header('Content-Type: application/json; charset=utf-8');

function jsonResponse(int $statusCode, array $data): void
{
    http_response_code($statusCode);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=your_db;charset=utf8mb4',
        'user',
        'password',
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]
    );

    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';
    $orderBy = $_GET['order_by'] ?? 'id';
    $orderDir = strtolower($_GET['order_dir'] ?? 'desc');

    $allowedColumns = ['id', 'name', 'email', 'created_at'];
    $allowedDirections = ['asc', 'desc'];

    if (!in_array($orderBy, $allowedColumns, true)) {
        $orderBy = 'id';
    }

    if (!in_array($orderDir, $allowedDirections, true)) {
        $orderDir = 'desc';
    }

    $where = [];
    $params = [];

    if ($search !== '') {
        $where[] = "(name LIKE :search1 OR email LIKE :search2)";
        $params[':search1'] = '%' . $search . '%';
        $params[':search2'] = '%' . $search . '%';
    }

    if ($status !== '') {
        $allowedStatuses = ['active', 'inactive'];

        if (!in_array($status, $allowedStatuses, true)) {
            jsonResponse(422, [
                'success' => false,
                'message' => 'Invalid status.'
            ]);
        }

        $where[] = "status = :status";
        $params[':status'] = $status;
    }

    $whereSql = '';

    if (!empty($where)) {
        $whereSql = 'WHERE ' . implode(' AND ', $where);
    }

    $sql = "
        SELECT id, name, email, status, created_at
        FROM users
        {$whereSql}
        ORDER BY {$orderBy} {$orderDir}
        LIMIT 50
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $users = $stmt->fetchAll();

    jsonResponse(200, [
        'success' => true,
        'data' => $users
    ]);

} catch (PDOException $e) {
    error_log('PDO error: ' . $e->getMessage());

    jsonResponse(500, [
        'success' => false,
        'message' => 'Internal error while reading the data.'
    ]);

} catch (Throwable $e) {
    error_log('Unexpected error: ' . $e->getMessage());

    jsonResponse(500, [
        'success' => false,
        'message' => 'Internal server error.'
    ]);
}

Conclusion

SQL injection is a serious flaw, but it is easy to prevent in PHP. The main rule is to never concatenate external values into an SQL query.

With PDO and prepared statements, input validation, an allowlist for sorting and proper error handling, your application is far safer against query manipulation.

Apply this protection to logins, sign-ups, filters, searches, APIs, admin panels and any other place that talks to the database. To put it all together in an API, see how to create a REST API in plain PHP, and for authentication, JWT authentication in PHP.

Frequently asked questions about SQL injection in PHP

What is SQL injection in PHP?

It is a flaw that happens when user input is inserted directly into an SQL query, letting an attacker change what the query does.

How do I prevent SQL injection in PHP?

Use PDO with prepared statements and pass the values as parameters instead of concatenating them into the SQL.

Does PDO prevent SQL injection?

Yes, when it is used with prepared statements and parameters. PDO keeps the SQL command separate from the values sent by the user.

Does addslashes protect against SQL injection?

It should not be your protection. Use prepared statements instead of escaping values by hand.

Do I still need to validate input with prepared statements?

Yes. Prepared statements protect the query; validation makes sure the data makes sense for your application.

Can I use LIKE with a prepared statement?

Yes. Build the value with % and pass it as a parameter, for example '%' . $search . '%'.

More in PHP