PDO Transactions: beginTransaction, commit, and rollBack
Lesson 22 of 43 in the PHP 8 learning path.
How do I insert a student and an enrollment so both succeed or neither does?
An enrollment is two writes that have to agree. The student row and the enrollment row should both exist, or neither should. A crash or a duplicate email between the two inserts would otherwise leave a student with no section, or a section pointing at a student that never committed. beginTransaction() starts that unit of work. Two prepared statements insert the student and the enrollment. commit() makes both durable. If either statement throws, rollBack() undoes the work that this transaction already did, and the exception is raised again for the boundary to handle.
The tables use InnoDB. MyISAM ignores transactions, so commit and rollBack would not protect those writes. The sample enrolls Amina Cruz into Lab safety briefing, prints status=committed, then tries the same email again. The unique key throws, the second transaction rolls back, and the student count stays 1.
Syntax & Parameters
$pdo->beginTransaction();
$pdo->commit();
$pdo->rollBack();
Example
<?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,
]);
}
function enrollStudent(PDO $pdo, string $fullName, string $email, int $lessonId): void
{
if ($lessonId < 1 || trim($fullName) === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException('Name, email, and lesson id are required.');
}
$pdo->beginTransaction();
try {
$student = $pdo->prepare('INSERT INTO students (full_name, email) VALUES (:full_name, :email)');
$student->execute(['full_name' => trim($fullName), 'email' => $email]);
$enrollment = $pdo->prepare('INSERT INTO enrollments (student_id, lesson_id) VALUES (:student_id, :lesson_id)');
$enrollment->execute(['student_id' => (int) $pdo->lastInsertId(), 'lesson_id' => $lessonId]);
$pdo->commit();
} catch (Throwable $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
throw $exception;
}
}
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');
$pdo->exec('CREATE TABLE IF NOT EXISTS students (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, full_name VARCHAR(120) NOT NULL, email VARCHAR(160) NOT NULL, UNIQUE KEY students_email_unique (email)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
$pdo->exec('CREATE TABLE IF NOT EXISTS enrollments (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, student_id INT UNSIGNED NOT NULL, lesson_id INT UNSIGNED NOT NULL, CONSTRAINT enrollments_student_fk FOREIGN KEY (student_id) REFERENCES students (id), CONSTRAINT enrollments_lesson_fk FOREIGN KEY (lesson_id) REFERENCES lessons (id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');
$email = 'amina.cruz.classroom@example.com';
$existing = $pdo->prepare('SELECT id FROM students WHERE email = :email');
$existing->execute(['email' => $email]);
$existingId = $existing->fetchColumn();
if ($existingId !== false) {
$pdo->prepare('DELETE FROM enrollments WHERE student_id = :id')->execute(['id' => $existingId]);
$pdo->prepare('DELETE FROM students WHERE id = :id')->execute(['id' => $existingId]);
}
$lesson = $pdo->prepare('INSERT INTO lessons (title, track, seats) VALUES (:title, :track, :seats)');
$lesson->execute(['title' => 'Lab safety briefing', 'track' => 'web', 'seats' => 24]);
$lessonId = (int) $pdo->lastInsertId();
enrollStudent($pdo, 'Amina Cruz', $email, $lessonId);
echo "status=committed\nstudent=Amina Cruz\nlesson=Lab safety briefing\n";
try {
enrollStudent($pdo, 'Amina Cruz', $email, $lessonId);
echo "retry=committed\n";
} catch (PDOException) {
error_log('Duplicate enrollment was rolled back.');
echo "retry=rolled_back\n";
}
$count = $pdo->prepare('SELECT COUNT(*) FROM students WHERE email = :email');
$count->execute(['email' => $email]);
echo 'students=' . $count->fetchColumn() . "\n";
} catch (Throwable $exception) {
error_log($exception instanceof PDOException ? 'Enrollment transaction failed.' : $exception->getMessage());
echo "The enrollment could not be saved. Please try again shortly.\n";
}
Expected Output
status=committed student=Amina Cruz lesson=Lab safety briefing retry=rolled_back students=1
Line-by-Line Walkthrough
- declare(strict_types=1) checks enrollStudent() for calls in this file, including the int lesson id.
- gradebook() uses exceptions, associative fetches, native prepares, and charset utf8mb4.
- enrollStudent() rejects a bad email, a blank name, or a lesson id below 1 before it starts a transaction.
- beginTransaction() opens the unit of work. Both inserts that follow belong to it.
- The first prepared statement inserts the student. The second inserts the enrollment using lastInsertId() from that same connection.
- commit() makes both rows durable. The engine is InnoDB, which is what makes the transaction real.
- If either statement throws, and a transaction is still open, rollBack() undoes it and the exception is thrown again.
- The runner creates the InnoDB tables, clears only the classroom email if it is already present, and inserts Lab safety briefing.
- The first enrollStudent() commits. The echoes print status=committed, the student, and the lesson.
- The second call hits the unique email, rolls back inside enrollStudent(), and the inner catch prints retry=rolled_back.
- The count of students with that email stays 1, which shows the failed retry did not add a row.
- The outer catch logs a fixed line for a PDOException and does not print getMessage() to the visitor.
Common Pitfalls & Security
A transaction protects the two inserts only on an engine that supports it. InnoDB does. A MyISAM table will appear to commit and will not roll back. The other failure is catching the error and forgetting rollBack(), which leaves the connection inside an open transaction for the rest of the request. SQL injection (SQLi) is unchanged by beginTransaction(): the name still has to be bound.
- Calling commit() after a failed statement, or skipping rollBack(), can leave a student row without an enrollment or hold locks until the connection closes.
- rollBack() when no transaction is open throws. Check inTransaction() first, as the sample does.
- Unsafe anti-pattern (do not ship): two separate inserts with no beginTransaction(). A duplicate email on the second insert leaves the first row behind.
- MyISAM ignores these calls. Create the tables with ENGINE=InnoDB, which the sample does.
- lastInsertId() is connection-specific. Read it on the same PDO, inside the transaction, before another insert replaces it.
- The unique-key error text names the index. Log a fixed sentence. Do not echo getMessage() to the student.
Best Practices & Modern Standards
On PHP 8.3, wrap the student insert and the enrollment insert in beginTransaction(), commit() only after both executes succeed, and rollBack() in the catch before you rethrow. Use InnoDB and foreign keys so an enrollment cannot point at a missing student. Keep both statements prepared.
Let the boundary decide the HTTP response. A duplicate email is a 422 the form can explain. A lost connection is a generic 500. The repository does not print SQL. Retry only when the operation is safe to repeat, and clear or detect the classroom fixture the way this runner clears one known email before the demonstration.
Real-World Use
The enrollment form for Amina Cruz must create her student row and a seat in Lab safety briefing together. enrollStudent() commits both. If the email is already registered, the second attempt rolls back and the count stays one. The desk can show "that email is already enrolled" without a half-written student. The lesson row remains, because it was inserted before the transaction that failed.
Frequently Asked Questions
Why does the retry print rolled_back?
The email is unique. The second insert throws, enrollStudent() calls rollBack(), and the catch prints retry=rolled_back. The count stays 1.
Why mention InnoDB?
InnoDB honors beginTransaction(), commit(), and rollBack(). MyISAM does not. The CREATE TABLE statements set ENGINE=InnoDB so the demonstration matches production.
Does a transaction stop SQL injection?
No. It groups writes. The inserts still use parameters for the name, the email, and the ids. Concatenated SQL is unsafe inside a transaction too.
What does the runner delete?
Only the student row for amina.cruz.classroom@example.com, and that student enrollments, so the file can be run again. It does not empty the lessons table.