Thuta Learning
PHP
AdvancedProgrammingBeginner

INSERT Data

PHPLesson 3035 min

What you'll walk away with

  • Prepare and execute an INSERT with an explicit column list and placeholders
  • Validate input with trim and filter_var before it reaches the database
  • Explain what execute(), rowCount() and lastInsertId() each return (lastInsertId is a string)
  • Declare a UNIQUE constraint and handle duplicates by catching a PDOException (SQLSTATE 23000)

Explain it simply

Explain it simply

An INSERT statement stores a new row. Contact form submissions, new user registrations and new products all end with an INSERT. The order of work matters: first validate what the visitor sent, then save it with a prepared statement, then tell the visitor what happened. If validation fails, nothing is inserted and the form is shown again with a helpful message.

The database answers with the id of the new row, which you can use to show a confirmation or to link related rows.

Problem → Why → Solution

The problem: blank rows, duplicates and silent failures

Without a plan, an INSERT happily stores whatever arrives. A visitor who submits the form with every field empty creates a blank row. A visitor who double-clicks, or refreshes the page after submitting, creates the same row twice. Two people registering the same email at the same instant both pass the 'is it taken?' check and both succeed. And when an insert does fail, a catch block that prints 'Something went wrong' without logging anything leaves you with no clue why.

fragile-insert.php
<?php
// Unsafe and fragile: no validation, no uniqueness rule, input pasted into the SQL
$pdo->query("INSERT INTO contacts (name, email, message)
             VALUES ('{$_POST['name']}', '{$_POST['email']}', '{$_POST['message']}')");

echo 'Contact message saved.';   // printed even if every field was empty

A good INSERT is a small pipeline

A good INSERT is the end of a small pipeline: validate the input, let the database enforce what only it can enforce (NOT NULL, UNIQUE), save through placeholders, and report the outcome honestly. Each stage catches a different kind of problem, and the last one, reporting, relies on exceptions rather than on a boolean that never turns false.

Core concept: INSERT, validation and constraints

INSERT adds a row. The safe shape is INSERT INTO table (col1, col2) VALUES (?, ?): name the columns, because without a column list the values must match the table's current column order and your code breaks silently when someone adds a column. Values go through placeholders, exactly as in SELECT, so quotes in a message never become SQL. You never write the id or created_at yourself when the database generates them.

execute() returns true when the statement ran and, with ERRMODE_EXCEPTION, it never returns false: a failure throws a PDOException instead, so an else branch that prints 'something went wrong' after execute() is dead code. After a successful INSERT, $stmt->rowCount() tells you how many rows were inserted (1 for a single row), and $pdo->lastInsertId() gives the id the database generated. lastInsertId() returns a string, belongs to the connection, and refers to the most recent insert on that connection, so read it right after the INSERT and cast it with (int).

Validate before you insert, and on the right side of the trust boundary: trim the text, check required fields, check the email shape with filter_var(), and compare lengths with the column size. Validation explains problems to the visitor politely. It cannot guarantee uniqueness, though: if two requests both check 'is this email taken?' at the same moment and both see 'no', both will insert it. Only a UNIQUE constraint in the database can make that impossible, so declare it and handle the failure.

A duplicate violates the constraint, PDO throws a PDOException, and its SQLSTATE is '23000', the class for integrity constraint violations (for statement errors it is in $e->errorInfo[0] and in getCode()). That code covers NOT NULL and foreign key failures too, so drivers add their own number when you must tell them apart (MySQL documents error 1062 for a duplicate entry). Catch the exception where you can translate it into a friendly message, and rethrow anything you do not recognise. When several INSERTs must succeed or fail together, wrap them in a transaction with beginTransaction(), commit() and rollBack().

Mental model: validate, insert, confirm
  1. Validate and trim the input
  2. prepare + execute with placeholders
  3. The database enforces its constraints
  4. lastInsertId() and redirect

Validation is polite help; constraints are the guarantee.

General pattern

pattern.php
<?php
$stmt = $pdo->prepare('INSERT INTO table_name (col_a, col_b) VALUES (?, ?)');
$stmt->execute([$valueA, $valueB]);

$stmt->rowCount();       // rows inserted
$pdo->lastInsertId();    // the generated id, as a string

List the columns and put one ? per value, then give execute() an array in the same order. Afterwards rowCount() reports the rows inserted and lastInsertId() returns the generated id as a string.

Example: validating and saving a contact message

This example handles two form submissions: the first is valid, and the second has blanks and a malformed email. The first passes the trimming and validation and gets saved, and the second is turned away before reaching the INSERT. Notice that the INSERT statement is prepared once and executed for each submission.

insert-contact.php
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec('CREATE TABLE contacts (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    name       TEXT NOT NULL,
    email      TEXT NOT NULL,
    message    TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)');

$submissions = [
    [
        'name' => ' Aung Aung ',
        'email' => 'aung@example.com',
        'message' => 'I want to learn PHP.',
    ],
    ['name' => '   ', 'email' => 'not-an-email', 'message' => ''],
];

$stmt = $pdo->prepare('INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)');

foreach ($submissions as $index => $form) {
    $number = $index + 1;
    $name = trim($form['name']);
    $email = trim($form['email']);
    $message = trim($form['message']);

    if ($name === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Submission $number rejected: please fix the form.\n";
        continue;
    }

    $stmt->execute([$name, $email, $message]);
    echo "Submission $number saved as row ", $pdo->lastInsertId(),
        ' (', $stmt->rowCount(), " row inserted)\n";
}

$count = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
echo "Rows in table: $count\n";

Code breakdown

  1. Line 21$stmt = $pdo->prepare('INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)');

    Lists three columns by name with one ? per value. id and created_at are left out because the database fills them in.

  2. Lines 25-27$name = trim($form['name']);

    trim() removes leading and trailing spaces. ' Aung Aung ' in the first submission becomes 'Aung Aung', while ' ' in the second becomes an empty string that the next step catches.

  3. Line 29if ($name === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {

    The required-field and email-shape checks. NOT NULL does not reject an empty string (''), so this check has to happen in PHP. continue skips the INSERT for this submission.

  4. Line 34$stmt->execute([$name, $email, $message]);

    The three values fill the three ? marks in order. Because of ERRMODE_EXCEPTION a failure throws a PDOException, so there is nothing to re-check after this line.

  5. Lines 35-36echo "Submission $number saved as row ", $pdo->lastInsertId(),

    lastInsertId() returns the id generated by the INSERT just made ('1') as a string, and rowCount() returns how many rows it inserted (1). This INSERT adds a single row, so both are exact.

  6. Line 39$count = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();

    A final check straight from the database: only the first submission was saved, so the table holds exactly one row.

You should see
Submission 1 saved as row 1 (1 row inserted)
Submission 2 rejected: please fix the form.
Rows in table: 1

Duplicates: a UNIQUE constraint and a catch

This code makes the email column UNIQUE. subscribe() tries the INSERT and, when the database refuses a duplicate, catches the PDOException and answers 'Already subscribed' only for SQLSTATE 23000, rethrowing any other PDOException. There is no 'is this email taken?' SELECT first; the database decides, so even two simultaneous requests produce exactly one success. Also note at the end that lastInsertId() is a string ('2').

unique-email.php
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec('CREATE TABLE subscribers (
    id    INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT NOT NULL UNIQUE
)');

function subscribe(PDO $pdo, string $email): string
{
    try {
        $stmt = $pdo->prepare('INSERT INTO subscribers (email) VALUES (?)');
        $stmt->execute([$email]);
        return 'Subscribed with id ' . $pdo->lastInsertId();
    } catch (PDOException $e) {
        if (($e->errorInfo[0] ?? '') === '23000') {
            return 'Already subscribed (' . $e->getMessage() . ')';
        }
        throw $e;
    }
}

foreach (['aye@example.com', 'aye@example.com', 'kyaw@example.com'] as $email) {
    echo $email, ': ', subscribe($pdo, $email), "\n";
}
var_dump($pdo->lastInsertId());

The message ('UNIQUE constraint failed: ...') is SQLite's wording, and MySQL words it differently, so test the SQLSTATE instead of the message text. For cases where a duplicate should simply be skipped, or turned into an update, each database has a shortcut, but the syntax differs.

GoalMySQL / MariaDBSQLite
Skip a duplicate quietlyINSERT IGNORE INTO ...INSERT OR IGNORE INTO ...
Update when it exists... ON DUPLICATE KEY UPDATE col = ...... ON CONFLICT (email) DO UPDATE SET col = ...
Duplicate error number1062 (per MySQL's documentation)19 (constraint), message says UNIQUE constraint failed
SQLSTATE23000 (expected)23000

Several rows: reuse one statement and use a transaction

When an order has several lines, prepare the statement once and execute it in a loop. A transaction guarantees that either all of them are saved or none: start with beginTransaction(), call commit() when everything worked, and rollBack() when one fails. In the code below the second order's middle line breaks NOT NULL, so its first line is undone too and only the first order's two rows remain.

transaction.php
<?php
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec('CREATE TABLE order_items (
    id    INTEGER PRIMARY KEY AUTOINCREMENT,
    item  TEXT NOT NULL,
    qty   INTEGER NOT NULL
)');

function saveOrder(PDO $pdo, array $lines): string
{
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare('INSERT INTO order_items (item, qty) VALUES (?, ?)');
        foreach ($lines as [$item, $qty]) {
            $stmt->execute([$item, $qty]);
        }
        $pdo->commit();
        return 'committed ' . count($lines) . ' lines';
    } catch (PDOException $e) {
        $pdo->rollBack();
        return 'rolled back';
    }
}

echo saveOrder($pdo, [['Notebook', 2], ['Pen', 10]]), "\n";
echo saveOrder($pdo, [['Ruler', 1], [null, 3], ['Eraser', 4]]), "\n";
$count = $pdo->query('SELECT COUNT(*) FROM order_items')->fetchColumn();
echo "Rows stored: $count\n";

// One INSERT with several rows
$stmt = $pdo->prepare('INSERT INTO order_items (item, qty) VALUES (?, ?), (?, ?)');
$stmt->execute(['Stapler', 1, 'Tape', 2]);
echo 'rowCount: ', $stmt->rowCount(), ', lastInsertId: ', $pdo->lastInsertId(), "\n";

Look at the final INSERT with two VALUES groups. rowCount() returns 2, but lastInsertId() depends on the database: SQLite returns the id of the last row inserted (4 here), while MySQL's documentation says it returns the first id generated by such a multi-row INSERT. So do not trust lastInsertId() after a multi-row INSERT; insert row by row when you need the ids.

After the INSERT: Post/Redirect/Get

On a web form, redirect after a successful INSERT instead of showing the thank-you page directly. If the POST response itself is shown, refreshing makes the browser resubmit the form and creates a second row. After a 303 redirect the browser fetches the new page with GET, so a refresh repeats only the GET. For more important actions, such as payments, add a one-time token as well so that network retries cannot repeat them either.

post-redirect-get.php
<?php
// contact.php: handle the form, then redirect so a refresh cannot submit it twice
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ...validate the input and run the INSERT shown above...

    header('Location: /contact-thanks.php', true, 303);   // 303 See Other
    exit;
}

// A GET request just shows the form (or the thank-you page)

In real projects

Where this shows up in real projects

Every sign-up, comment, order and upload ends in an INSERT. In real applications the INSERT sits in a small function or repository method that takes validated values and returns the new id or throws a domain exception such as EmailAlreadyRegistered, so controllers read like plain English. Frameworks wrap this too: Laravel's Model::create() and Doctrine's persist() ultimately run an INSERT with bound parameters, and their migrations declare the UNIQUE indexes that make duplicates impossible.

Concurrency is the reason for the discipline in this lesson: on a busy site two requests really do arrive at the same moment, retries happen when networks time out, and impatient visitors double-click. Applications cope with all three by combining validation, database constraints, transactions and idempotent handling such as Post/Redirect/Get, and by logging every failure with enough context to debug it later.

Common mistakes

Common mistakes

1. Inserting without validating

NOT NULL rejects only NULL and accepts an empty string (''), so you must trim() and test for emptiness in PHP. If you do not, blank rows pile up.

2. Checking uniqueness only in PHP

A SELECT-then-INSERT pattern lets another request slip in between the check and the insert, so duplicates can appear. Make the column UNIQUE and catch SQLSTATE 23000; it is the only fully reliable approach.

3. Relying on an else branch after execute()

With ERRMODE_EXCEPTION a failing execute() throws instead of returning false, so the else in if (execute()) {...} else { 'Something went wrong' } never runs. Use try/catch, log the exception and show the visitor a generic message.

4. Misusing lastInsertId()

lastInsertId() returns a string, so cast it with (int); it belongs to one connection and changes when another insert intervenes, so read it right after the INSERT. After a multi-row INSERT it differs between databases, so do not rely on it.

5. Writing INSERT without a column list

INSERT INTO contacts VALUES (...) depends on the table's current column order, so adding one column can raise an error or put values into the wrong columns. Always name the columns.

Best practices

Best practices

  • Put the INSERT in a function or repository method that accepts only validated values and returns the id.
  • Declare UNIQUE constraints for data that must not repeat, catch SQLSTATE 23000 and translate it into a friendly message.
  • When several rows must succeed together use a transaction and commit or roll back as a whole.
  • After a web-form INSERT do a 303 redirect (Post/Redirect/Get), and keep the failure detail in the log.

Mini challenge

Mini challenge: a registration that handles duplicates

Write a register() function for a users table. It throws different exceptions for invalid input and for a repeated username or email, and returns the new id as an int on success.

  • final class DuplicateUserException extends RuntimeException
  • register(PDO $pdo, string $username, string $email): int trims, and throws InvalidArgumentException for a blank username or an invalid email
  • Run the INSERT with named placeholders in try/catch; for SQLSTATE 23000 throw DuplicateUserException with the PDOException as previous, otherwise rethrow
  • Both username and email are UNIQUE in the users table; loop over five attempts, print each result, and finish by listing the stored usernames in id order
register.php
<?php
declare(strict_types=1);

// TODO: final class DuplicateUserException extends RuntimeException

// TODO: function register(PDO $pdo, string $username, string $email): int
//   - trim both values; a blank username or an invalid email -> InvalidArgumentException
//   - INSERT with named placeholders inside try/catch
//   - SQLSTATE '23000' (in $e->errorInfo[0]) -> DuplicateUserException, keeping the
//     PDOException as $previous; any other PDOException is rethrown unchanged
//   - return the new id as an int

$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);

// TODO: CREATE TABLE users: id (auto primary key), username (required, UNIQUE),
//       email (required, UNIQUE)

$attempts = [
    ['aye', 'aye@example.com'],
    ['kyaw', 'kyaw@example.com'],
    ['aye', 'other@example.com'],
    ['', 'x'],
    ['zaw', 'kyaw@example.com'],
];

// TODO: for each attempt print "'<username>' <<email>>: " followed by
//       "registered with id N" or "refused - <message>" (catch the two exception types)

// TODO: print "Users stored: " and the usernames in id order, separated by ", "

Expected: 'aye' <aye@example.com>: registered with id 1 'kyaw' <kyaw@example.com>: registered with id 2 'aye' <other@example.com>: refused - 'aye' or 'other@example.com' is already registered '' <x>: refused - Invalid username or email 'zaw' <kyaw@example.com>: refused - 'zaw' or 'kyaw@example.com' is already registered Users stored: aye, kyaw

Show hint

Test the SQLSTATE with ($e->errorInfo[0] ?? '') === '23000'. Calling the function directly inside echo would print half a line before the exception is thrown, so store the result in a variable first.

Show solution
register.php
<?php
declare(strict_types=1);

final class DuplicateUserException extends RuntimeException {}

function register(PDO $pdo, string $username, string $email): int
{
    $username = trim($username);
    $email = trim($email);
    if ($username === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new InvalidArgumentException('Invalid username or email');
    }

    try {
        $sql = 'INSERT INTO users (username, email) VALUES (:username, :email)';
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':username' => $username, ':email' => $email]);
    } catch (PDOException $e) {
        if (($e->errorInfo[0] ?? '') === '23000') {
            throw new DuplicateUserException(
                "'$username' or '$email' is already registered",
                0,
                $e
            );
        }
        throw $e;
    }

    return (int) $pdo->lastInsertId();
}

$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
$pdo = new PDO('sqlite::memory:', null, null, $options);
$pdo->exec('CREATE TABLE users (
    id       INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL UNIQUE,
    email    TEXT NOT NULL UNIQUE
)');

$attempts = [
    ['aye', 'aye@example.com'],
    ['kyaw', 'kyaw@example.com'],
    ['aye', 'other@example.com'],
    ['', 'x'],
    ['zaw', 'kyaw@example.com'],
];

foreach ($attempts as [$username, $email]) {
    echo "'$username' <$email>: ";
    try {
        $id = register($pdo, $username, $email);
        echo "registered with id $id\n";
    } catch (DuplicateUserException | InvalidArgumentException $e) {
        echo 'refused - ', $e->getMessage(), "\n";
    }
}

$rows = $pdo->query('SELECT username FROM users ORDER BY id');
$names = $rows->fetchAll(PDO::FETCH_COLUMN);
echo 'Users stored: ', implode(', ', $names), "\n";

Quick quiz 1 / 3

With ERRMODE_EXCEPTION, what happens when the INSERT fails in if ($stmt->execute()) { echo 'saved'; } else { echo 'failed'; }?

Quick quiz 2 / 3

What type does $pdo->lastInsertId() return, and when should you read it?

Quick quiz 3 / 3

What is the most reliable way to stop duplicate emails?

What to remember

  • Prepare and execute INSERT with an explicit column list and placeholders, and validate first with trim and filter_var (NOT NULL does not reject an empty string).
  • In exception mode a failing execute() throws; rowCount() is the rows inserted, and lastInsertId() is a string id to read immediately.
  • Guarantee uniqueness with a UNIQUE constraint and handle SQLSTATE 23000; MySQL and SQLite differ in the duplicate error number and in INSERT IGNORE versus OR IGNORE.
  • Use a transaction for several rows and Post/Redirect/Get for web forms.

PDO Prepared Statements — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

INSERT Data | Thuta Learning