PHP 8 Intermediate PDO & Security · 9 min read

PHP PDO INSERT with Prepared Statements

Lesson 19 of 43 in the PHP 8 learning path.

How do I insert a row with PHP PDO without SQL injection?

An INSERT that glues a title into the SQL string is SQL injection (SQLi). The quote in a lesson title changes the statement the server parses. A prepared INSERT keeps the statement fixed: INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats). The values travel in a bound array, ['title' => $title, 'track' => $track, 'seats' => $seats], and execute() sends them separately. lastInsertId() returns the new autoincrement id as a string. The sample prints that id and reads the row back so the stored title, track, and seats are what the script reports.

Validation happens before execute(). The title and track are trimmed and limited with mb_strlen() in UTF-8, and seats has to be an int from 1 through 500. A request string never reaches the database as a column type by accident: the method signature already requires string, string, and int, and the file declares strict types.

Syntax & Parameters

Syntax
INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats)

Example

src/LessonRepository.php
<?php

declare(strict_types=1);

function gradebook(): PDO
{
    $password = getenv('GRADEBOOK_PASSWORD');
    if ($password === false) {
        throw new RuntimeException('Set GRADEBOOK_PASSWORD for the grade book database user.');
    }
    $host = getenv('GRADEBOOK_HOST') ?: '127.0.0.1';
    $database = getenv('GRADEBOOK_DATABASE') ?: 'gradebook';
    $user = getenv('GRADEBOOK_USER') ?: 'gradebook_app';
    return new PDO("mysql:host={$host};dbname={$database};charset=utf8mb4", $user, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
}
final class LessonRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function insert(string $title, string $track, int $seats): string
    {
        $title = trim($title);
        $track = trim($track);
        if ($title === '' || mb_strlen($title, 'UTF-8') > 160) {
            throw new InvalidArgumentException('Title must be 1 to 160 characters.');
        }
        if ($track === '' || mb_strlen($track, 'UTF-8') > 40) {
            throw new InvalidArgumentException('Track must be 1 to 40 characters.');
        }
        if ($seats < 1 || $seats > 500) {
            throw new InvalidArgumentException('Seats must be between 1 and 500.');
        }
        $statement = $this->pdo->prepare(
            'INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats)'
        );
        $bound = [
            'title' => $title,
            'track' => $track,
            'seats' => $seats,
        ];
        $statement->execute($bound);
        return $this->pdo->lastInsertId();
    }
}
try {
    $pdo = gradebook();
    $pdo->exec('CREATE TABLE IF NOT EXISTS lessons (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(160) NOT NULL, track VARCHAR(40) NOT NULL, seats SMALLINT UNSIGNED NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
    $id = (new LessonRepository($pdo))->insert('Lab safety briefing', 'web', 24);
    $check = $pdo->prepare('SELECT title, track, seats FROM lessons WHERE id = :id');
    $check->execute(['id' => $id]);
    $row = $check->fetch() ?: throw new RuntimeException('The inserted lesson could not be read back.');
    echo 'inserted=' . $id . "\n";
    echo 'title=' . $row['title'] . "\n";
    echo 'track=' . $row['track'] . "\n";
    echo 'seats=' . $row['seats'] . "\n";
} catch (InvalidArgumentException $exception) {
    echo $exception->getMessage() . "\n";
} catch (PDOException) {
    error_log('Lesson insert failed.');
    echo "The lesson could not be saved. Please try again shortly.\n";
} catch (RuntimeException $exception) {
    error_log($exception->getMessage());
    echo "The lesson could not be saved. Please try again shortly.\n";
}

Expected Output

inserted=1
title=Lab safety briefing
track=web
seats=24

Line-by-Line Walkthrough

  1. declare(strict_types=1) rejects a string seat count at the insert() call in this file instead of coercing it.
  2. gradebook() connects with utf8mb4, ERRMODE_EXCEPTION, FETCH_ASSOC, and ATTR_EMULATE_PREPARES set to false.
  3. insert() trims the title and track and rejects an empty value or a length above the column limit, using mb_strlen() in UTF-8.
  4. Seats must be an int from 1 through 500 before any SQL runs.
  5. The prepared SQL is INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats).
  6. $bound holds the three values, and execute($bound) sends them as data rather than as SQL text.
  7. lastInsertId() returns the new id as a string. That string is the method result.
  8. The runner creates the table when it is missing, inserts Lab safety briefing on the web track with 24 seats, and selects that id back.
  9. The echoes print inserted= and the title, track, and seats read from the row, so the output is what was stored.
  10. InvalidArgumentException is safe to show. A PDOException is logged without getMessage() and the visitor sees a generic sentence.

Common Pitfalls & Security

SQL injection (SQLi) on an INSERT is the same bug as on a SELECT: the title is parsed as SQL if you concatenate it. Binding :title closes that. A second mistake is trusting lastInsertId() from a different connection, or printing the driver error, which includes the statement the attacker is trying to shape. Validate types before execute() so a bad seat count never becomes a query.

  • Unsafe anti-pattern (do not ship): "INSERT INTO lessons (title) VALUES ('" . $title . "')" concatenates the title into SQL. Use the bound array in the sample.
  • lastInsertId() is per connection and returns a string. Cast it when the next call expects an int, and call it on the same PDO that ran the INSERT.
  • Skipping the length check lets a huge title throw a SQL error at the boundary. The 160 and 40 character limits match the columns and fail as validation.
  • mb_strlen() is the character count. strlen() would reject José-style titles for the wrong reason, or accept too many characters.
  • Echoing $exception->getMessage() from PDOException leaks schema details that help a SQLi attempt. The sample logs a fixed line instead.
  • HTML still needs htmlspecialchars when the new title is printed on a page. The insert being parameterized does not encode HTML.

Best Practices & Modern Standards

On PHP 8.3, type the insert method, validate ranges before execute(), and bind a named array that a reviewer can match to the parameters. Keep ATTR_EMULATE_PREPARES false and the connection in exception mode so a constraint failure throws instead of returning false. Store utf8mb4 so the title can contain the characters teachers actually type.

Return the new id to the controller and redirect to the lesson page. Do not build the next URL by concatenating raw input. The id from lastInsertId() is the server value. Pair this write with the HTML escape on the confirmation page and with the SELECT that loads the row by that id.

Real-World Use

The enrollment desk adds a lesson named Lab safety briefing on the web track with 24 seats. insert() checks the strings and the seat count, runs the prepared INSERT, and returns the new id. On an empty lessons table that id is 1. The confirmation page loads the row by that id and escapes the title for HTML. A title with a quote stays a title, because it was bound rather than pasted into the statement.

Frequently Asked Questions

What does lastInsertId() return?

A string. On an empty lessons table the sample prints inserted=1. The next insert on that table receives the next autoincrement value. Cast to int when you pass the id to find().

Why validate before execute()?

So a blank title or a seat count of 0 becomes a validation message instead of a constraint error. The types are already enforced by the signature under strict_types. The range checks are your rules.

Where is the bound array?

$bound maps title, track, and seats to the parameters :title, :track, and :seats. execute($bound) sends that array. The SQL text does not contain the title.

Does this stop XSS as well as SQLi?

It stops SQL injection on this INSERT. Cross-site scripting is a separate step: escape the title with htmlspecialchars when a page prints it.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…