# 警告：mysqli::set_charset()：无法获取 mysqli，位于 /var/www/app/src/Database/MysqliConnection.php 第 22 行

- **ID:** `php/mysqli-connection-character-set`
- **领域:** php
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

mysqli::set_charset() 方法在一个未连接或连接失败的对象上调用，通常是由于主机、凭据错误或数据库服务器不可用。

## 版本兼容性

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

## 解决方案

1. ```
   在设置字符集之前检查连接状态：`if ($mysqli->connect_errno) { die('连接失败：' . $mysqli->connect_error); } $mysqli->set_charset('utf8mb4');`
   ```
2. ```
   验证连接字符串中的 MySQL 主机、端口、用户名和密码；使用 `mysql -h host -P port -u user -p` 从命令行测试。
   ```
3. ```
   确保 MySQL 服务器正在运行并可访问；检查 my.cnf 中的防火墙规则和 bind-address（例如，为远程连接设置 `bind-address = 0.0.0.0`）。
   ```

## 无效尝试

- **** — The extension is loaded; the issue is that the connection object is invalid. (80% 失败率)
- **** — The server may be fine; the error is in the application configuration. (85% 失败率)
- **** — The error is about connection establishment, not script execution duration. (90% 失败率)
