HY000/2002 php network_error ai_generated true

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

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

ID: php/mysqli-connection-timeout

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
1证据数
2024-03-12首次发现

版本兼容性

版本状态引入弃用备注
PHP 8.1 active
PHP 8.2 active
PHP 8.3 active
MySQL 8.0 active
MariaDB 10.6 active

根因分析

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

English

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.

generic

官方文档

https://www.php.net/manual/en/mysqli.construct.php

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 75% 失败

    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.

  2. 60% 失败

    Restarting the web server or PHP-FPM does not resolve network-level issues like firewall rules or DNS resolution problems.

  3. 50% 失败

    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.