OpenCart v3.x支付时MySQL server has gone away错误求解决
解决方案针对OpenCart v3.x MySQL server has gone away(2006)支付回调问题
修复数据库驱动的自动重连逻辑
OpenCart默认的mysqli驱动未处理连接断开后的重连机制,支付回调这类可能耗时较长的请求容易触发连接超时。修改system/library/db/mysqli.php的query方法,在执行查询前添加连接校验与重连逻辑:public function query($sql) { // 检查连接有效性,失效则重新建立连接 if (!$this->connection->ping()) { $this->connection->close(); $this->connection = new mysqli($this->hostname, $this->username, $this->password, $this->database, $this->port); if ($this->connection->connect_error) { throw new \Exception('Error: ' . $this->connection->connect_error . '<br />Error No: ' . $this->connection->connect_errno); } $this->connection->set_charset($this->charset); } // 原有查询逻辑保留 $query = $this->connection->query($sql); // ... 后续原有代码不变 }注:如果错误栈指向的第48行是查询执行代码,把重连逻辑加在该行之前即可。
重置支付回调的数据库连接
支付回调脚本启动时,主动重置数据库连接,避免复用闲置断开的连接。在对应支付模块的回调控制器(如catalog/controller/extension/payment/paypal.php、debitcard.php)的回调方法开头添加:// 重新初始化数据库连接 $this->db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT);调整MySQL服务器超时参数
仅修改OpenCart的config.php可能无效,需直接调整MySQL配置文件(my.cnf/my.ini):wait_timeout = 300 interactive_timeout = 300重启MySQL服务后,执行
SHOW VARIABLES LIKE '%timeout%';确认参数生效。根据服务器实际负载,可适当延长超时时间(不建议超过3600秒)。排查回调执行时长并优化逻辑
手动请求正常但自动回调失败,可能是回调执行时间过长导致连接闲置超时。在回调逻辑中添加执行时长日志:$start = microtime(true); // 回调核心逻辑代码 $this->log->write('Callback execution duration: ' . round(microtime(true) - $start, 2) . 's');如果时长接近MySQL的wait_timeout,需优化逻辑:减少冗余查询、将非核心操作(如邮件通知)改为异步处理。
主动关闭闲置连接
在支付回调流程结束后,若无需后续数据库操作,主动关闭连接:$this->db->connection->close();
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

