PHP

Auto-Reconnect on "MySQL has gone away"

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Long-running daemons sometimes lose their MySQL connection mid-run. Wrap your DB calls to retry once after a transient connection-lost error.
PHP
Raw
<?php
function withDbRetry(callable $reconnect, callable $work): mixed {
    try {
        return $work();
    } catch (PDOException $e) {
        $transient = str_contains($e->getMessage(), 'gone away')
                  || str_contains($e->getMessage(), 'Lost connection')
                  || str_contains($e->getMessage(), 'Broken pipe');
        if (!$transient) throw $e;
        $reconnect();        // caller hands us a fresh connection
        return $work();      // single retry — let the next failure bubble
    }
}

// usage in a long-running worker loop:
$rows = withDbRetry(
    fn() => $GLOBALS['db'] = pdoConnect(...),
    fn() => $GLOBALS['db']->query('SELECT id FROM jobs WHERE status = "pending"')->fetchAll()
);
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.