# PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server during query in /var/www/app/src/Database/QueryBuilder.php on line 78

- **ID:** `php/pdo-mysql-query-timeout`
- **Domain:** php
- **Category:** network_error
- **Error Code:** `2013`
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A long-running query exceeds MySQL's wait_timeout or net_read_timeout, or the MySQL server restarted or crashed mid-query, causing the connection to drop.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 7.4 | active | — | — |
| 8.0 | active | — | — |
| 8.1 | active | — | — |
| 8.2 | active | — | — |
| 8.3 | active | — | — |

## Workarounds

1. **Increase MySQL's wait_timeout and net_read_timeout in my.cnf: [mysqld] wait_timeout = 600 net_read_timeout = 600. Restart MySQL: sudo systemctl restart mysql** (85% success)
   ```
   Increase MySQL's wait_timeout and net_read_timeout in my.cnf: [mysqld] wait_timeout = 600 net_read_timeout = 600. Restart MySQL: sudo systemctl restart mysql
   ```
2. **Optimize the slow query by adding indexes or splitting it into smaller chunks. Example: $chunks = array_chunk($largeArray, 1000); foreach ($chunks as $chunk) { // execute query with chunk }** (80% success)
   ```
   Optimize the slow query by adding indexes or splitting it into smaller chunks. Example: $chunks = array_chunk($largeArray, 1000); foreach ($chunks as $chunk) { // execute query with chunk }
   ```
3. **Implement a retry mechanism with exponential backoff in PHP: for ($attempt = 1; $attempt <= 3; $attempt++) { try { $stmt->execute(); break; } catch (PDOException $e) { if ($e->getCode() !== '2013') throw $e; usleep(pow(2, $attempt) * 100000); } }** (75% success)
   ```
   Implement a retry mechanism with exponential backoff in PHP: for ($attempt = 1; $attempt <= 3; $attempt++) { try { $stmt->execute(); break; } catch (PDOException $e) { if ($e->getCode() !== '2013') throw $e; usleep(pow(2, $attempt) * 100000); } }
   ```

## Dead Ends

- **** — PDO timeout affects connection attempts, not query execution. The MySQL server's own timeout settings are the limiting factor. (85% fail)
- **** — Persistent connections can help with connection overhead but do not prevent timeouts during queries. (90% fail)
