# PDOException: SQLSTATE[HY000] [2006] MySQL server has gone away in /var/www/app/src/Database/Connection.php:42

- **ID:** `php/pdo-mysql-server-has-gone-away`
- **Domain:** php
- **Category:** network_error
- **Error Code:** `2006`
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

The MySQL server closed the connection due to a timeout (wait_timeout or interactive_timeout), a packet size exceeding max_allowed_packet, or a server crash/restart, and the PHP PDO connection was not re-established.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| PHP 7.4 | active | — | — |
| PHP 8.1 | active | — | — |
| PHP 8.2 | active | — | — |
| MySQL 5.7 | active | — | — |
| MySQL 8.0 | active | — | — |

## Workarounds

1. **Increase MySQL's wait_timeout and interactive_timeout in my.cnf, e.g., set wait_timeout=28800; interactive_timeout=28800. Then restart MySQL.** (75% success)
   ```
   Increase MySQL's wait_timeout and interactive_timeout in my.cnf, e.g., set wait_timeout=28800; interactive_timeout=28800. Then restart MySQL.
   ```
2. **Increase max_allowed_packet in my.cnf to handle large queries, e.g., set max_allowed_packet=64M. Restart MySQL.** (70% success)
   ```
   Increase max_allowed_packet in my.cnf to handle large queries, e.g., set max_allowed_packet=64M. Restart MySQL.
   ```
3. **Implement connection retry logic in PHP: catch the exception and reconnect using a new PDO instance. Example:
try {
    $stmt = $pdo->query('SELECT 1');
} catch (\PDOException $e) {
    if ($e->getCode() == 2006) {
        $pdo = new PDO($dsn, $user, $pass);
        $stmt = $pdo->query('SELECT 1');
    }
}** (90% success)
   ```
   Implement connection retry logic in PHP: catch the exception and reconnect using a new PDO instance. Example:
try {
    $stmt = $pdo->query('SELECT 1');
} catch (\PDOException $e) {
    if ($e->getCode() == 2006) {
        $pdo = new PDO($dsn, $user, $pass);
        $stmt = $pdo->query('SELECT 1');
    }
}
   ```

## Dead Ends

- **** — The error is caused by MySQL's timeout, not PHP's execution time; changing PHP settings does not prevent the server from closing idle connections. (70% fail)
- **** — Persistent connections can mask the issue but may lead to stale connections being reused, causing the same error later; they also consume server resources. (50% fail)
- **** — Restarting temporarily reopens connections, but the underlying timeout or packet size issue remains, causing the error to recur. (80% fail)
