# Warning: mysqli::__construct(): (HY000/2002): Connection timed out in /var/www/app/src/Database/Connection.php:15

- **ID:** `php/mysqli-connection-timeout`
- **Domain:** php
- **Category:** network_error
- **Error Code:** `HY000/2002`
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

PHP's MySQLi extension fails to establish a TCP connection to the MySQL server within the configured timeout period, often due to network latency, firewall blocking, or incorrect host/port.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| PHP 8.1 | active | — | — |
| PHP 8.2 | active | — | — |
| PHP 8.3 | active | — | — |
| MySQL 8.0 | active | — | — |
| MariaDB 10.6 | active | — | — |

## Workarounds

1. **Increase the MySQLi connection timeout in the connection code: $mysqli = new mysqli('host', 'user', 'pass', 'db', 3306, null, 10); where the last parameter is timeout in seconds.** (85% success)
   ```
   Increase the MySQLi connection timeout in the connection code: $mysqli = new mysqli('host', 'user', 'pass', 'db', 3306, null, 10); where the last parameter is timeout in seconds.
   ```
2. **Check network connectivity: run 'telnet <mysql_host> 3306' from the PHP server. If it fails, adjust firewall rules (e.g., 'ufw allow 3306' on Ubuntu) or verify the MySQL server's bind-address is not 127.0.0.1.** (90% success)
   ```
   Check network connectivity: run 'telnet <mysql_host> 3306' from the PHP server. If it fails, adjust firewall rules (e.g., 'ufw allow 3306' on Ubuntu) or verify the MySQL server's bind-address is not 127.0.0.1.
   ```
3. **Use persistent connections with mysqli: p:host to reuse connections and reduce timeout issues, but ensure MySQL's wait_timeout is high enough.** (70% success)
   ```
   Use persistent connections with mysqli: p:host to reuse connections and reduce timeout issues, but ensure MySQL's wait_timeout is high enough.
   ```

## Dead Ends

- **** — Increasing PHP's default_socket_timeout in php.ini does not affect MySQLi connection timeout; MySQLi uses its own timeout settings via MYSQLI_OPT_CONNECT_TIMEOUT. (75% fail)
- **** — Restarting the web server or PHP-FPM does not resolve network-level issues like firewall rules or DNS resolution problems. (60% fail)
- **** — Adding 'localhost' instead of '127.0.0.1' may switch from TCP to Unix socket, but if the socket path is wrong, it still fails. (50% fail)
