A long-lived PHP worker can retain a PDO object after MySQL closes the idle connection. Check the connection before beginning the unit of work and replace it if that check fails. Once a transaction has executed a write, do not retry automatically unless the operation is explicitly idempotent.
Last updated: October 10, 2026.
<?php
function connect(): PDO
{
return new PDO(getenv('MYSQL_DSN'), getenv('MYSQL_USER'),
getenv('MYSQL_PASSWORD'), [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
}
try {
$pdo->query('SELECT 1');
} catch (PDOException) {
$pdo = connect(); // Safe here: no transaction or write has started.
}
$pdo->beginTransaction();
try {
$statement = $pdo->prepare('UPDATE jobs SET status = ? WHERE id = ?');
$statement->execute(['done', $jobId]);
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) $pdo->rollBack();
throw $error;
}Create the initial PDO connection when the worker starts or immediately before this block. The preflight query adds a round trip, so use it for workers that may remain idle; short request-per-process applications can usually open a fresh connection for each request instead.
Why idle connections disappear
MySQL’s server-has-gone-away guidance lists idle timeout as a common cause. Network devices, server restarts, oversized packets, and process termination can produce similar symptoms. Compare the failure timing with wait_timeout, but do not raise a global timeout merely to preserve abandoned application connections.
Release connections promptly and configure the application pool for the workload. A framework may wrap the original PDO exception, so detect connection loss using its documented exception API rather than matching only an English message.
Do not retry an uncertain commit blindly
The PHP PDO transaction documentation shows that a transaction starts with beginTransaction() and ends with commit() or rollBack(). If the connection is lost after a write or during commit, the client may not know whether the server committed it. Replaying the work can create duplicate effects.
Use unique operation keys, constraints, and idempotent commands when retries are required. Continue with diagnosing MySQL connections, connecting with PHP, and fixing authentication errors.