# 警告: mysqli::__construct(): (HY000/2002): 连接超时，位于 /var/www/app/src/Database/Connection.php:15

- **ID:** `php/mysqli-connection-timeout`
- **领域:** php
- **类别:** network_error
- **错误码:** `HY000/2002`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

PHP的MySQLi扩展在配置的超时时间内无法与MySQL服务器建立TCP连接，通常由网络延迟、防火墙阻止或主机/端口错误导致。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| PHP 8.1 | active | — | — |
| PHP 8.2 | active | — | — |
| PHP 8.3 | active | — | — |
| MySQL 8.0 | active | — | — |
| MariaDB 10.6 | active | — | — |

## 解决方案

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.
   ```
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.
   ```
3. ```
   Use persistent connections with mysqli: p:host to reuse connections and reduce timeout issues, but ensure MySQL's wait_timeout is high enough.
   ```

## 无效尝试

- **** — 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% 失败率)
- **** — Restarting the web server or PHP-FPM does not resolve network-level issues like firewall rules or DNS resolution problems. (60% 失败率)
- **** — 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% 失败率)
