MySQLi 连接
概述
MySQLi(MySQL Improved)是 PHP 访问 MySQL 数据库的专用扩展。提供面向对象和面向过程两种 API。相比 PDO,MySQLi 提供了更多 MySQL 特有的功能,如多查询、异步查询等。推荐使用面向对象 API。
适用场景
- MySQL 数据库专用项目
- 需要 MySQL 特有功能
- 需要多查询支持
- 需要 MySQLi 特定优化
基础概念
连接方式
| 方式 | 面向对象 | 面向过程 |
|---|---|---|
| 构造函数 | new mysqli() | mysqli_connect() |
| 错误处理 | $mysqli->connect_error | mysqli_connect_error() |
| 关闭 | $mysqli->close() | mysqli_close() |
推荐
推荐使用面向对象 API,更符合现代 PHP 编程风格。
语法与代码示例
面向对象连接
php
<?php
declare(strict_types=1);
// 基本连接
$mysqli = new mysqli('localhost', 'root', 'password', 'myapp');
if ($mysqli->connect_errno()) {
die("连接失败: {$mysqli->connect_error}");
}
echo "连接成功,MySQL 版本: {$mysqli->server_info}\n";
// 设置字符集
$mysqli->set_charset('utf8mb4');
// 关闭连接
$mysqli->close();带端口和 Socket 连接
php
<?php
// 指定端口
$mysqli = new mysqli('localhost', 'root', 'password', 'myapp', 3306);
// 使用 Unix Socket
$mysqli = new mysqli('localhost', 'root', 'password', 'myapp', null, '/var/run/mysqld/mysqld.sock');
// 连接选项
$mysqli = new mysqli();
$mysqli->init();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$mysqli->real_connect('localhost', 'root', 'password', 'myapp');面向过程连接
php
<?php
$mysqli = mysqli_connect('localhost', 'root', 'password', 'myapp');
if (!$mysqli) {
die("连接失败: " . mysqli_connect_error());
}
// 使用
$result = mysqli_query($mysqli, 'SELECT 1');
var_dump(mysqli_fetch_assoc($result));
mysqli_close($mysqli);持久连接
php
<?php
// MySQLi 持久连接(主机名前加 'p:')
$mysqli = new mysqli('p:localhost', 'root', 'password', 'myapp');
// 或者面向过程
$mysqli = mysqli_connect('p:localhost', 'root', 'password', 'myapp');连接选项设置
php
<?php
$mysqli = new mysqli();
$mysqli->init();
// 设置连接超时
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
// 设置读取超时
$mysqli->options(MYSQLI_OPT_READ_TIMEOUT, 30);
// 启用本地 infile
$mysqli->options(MYSQLI_OPT_LOCAL_INFILE, true);
// 连接
$mysqli->real_connect('localhost', 'root', 'password', 'myapp');实战示例
MySQLi 连接管理类
php
<?php
declare(strict_types=1);
class MySqlConnection
{
private ?mysqli $mysqli = null;
public function __construct(
private string $host = 'localhost',
private string $username = 'root',
private string $password = '',
private string $database = '',
private int $port = 3306,
private string $socket = '',
) {}
public function connect(): mysqli
{
if ($this->mysqli !== null) {
return $this->mysqli;
}
$this->mysqli = new mysqli(
$this->host,
$this->username,
$this->password,
$this->database,
$this->port,
$this->socket ?: null
);
if ($this->mysqli->connect_errno()) {
throw new RuntimeException(
"MySQL 连接失败: [{$this->mysqli->connect_errno}] {$this->mysqli->connect_error}"
);
}
$this->mysqli->set_charset('utf8mb4');
return $this->mysqli;
}
public function getConnection(): mysqli
{
return $this->connect();
}
public function close(): void
{
if ($this->mysqli !== null) {
$this->mysqli->close();
$this->mysqli = null;
}
}
public function ping(): bool
{
if ($this->mysqli === null) return false;
return $this->mysqli->ping();
}
}
// 使用
$db = new MySqlConnection('localhost', 'root', 'pass', 'myapp');
$mysqli = $db->connect();注意事项
连接超时
php
<?php
// MySQLi 连接超时由 options() 设置
$mysqli = new mysqli();
$mysqli->init();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 3);
$mysqli->real_connect('localhost', 'root', 'pass', 'myapp');
// 同时确保 php.ini 中的 default_socket_timeout 足够大MySQLi vs PDO
php
<?php
// MySQLi 优势:MySQL 特有功能、multi_query、异步查询
// PDO 优势:多数据库支持、统一的预处理语法、命名参数
// 如果项目只使用 MySQL,MySQLi 是很好的选择
// 如果可能切换数据库,使用 PDO最佳实践
1. 统一使用面向对象 API
php
<?php
// 好:面向对象
$mysqli = new mysqli('localhost', 'root', 'pass', 'app');
$result = $mysqli->query('SELECT 1');
// 不好:面向过程
$mysqli = mysqli_connect('localhost', 'root', 'pass', 'app');
$result = mysqli_query($mysqli, 'SELECT 1');2. 始终检查连接错误
php
<?php
if ($mysqli->connect_errno()) {
error_log("MySQL 连接失败: {$mysqli->connect_error}");
// 返回友好错误给用户
die('数据库连接失败,请稍后重试');
}进阶用法
调试与测试技巧
php
<?php
declare(strict_types=1);
// 单元测试辅助函数
function createTestResource(): mixed
{
return match (true) {
default => new stdClass(),
};
}
// 调试输出函数
function debugOutput(mixed , string = ''): void
{
= ? ": " : '';
.= print_r(, true);
fwrite(STDERR, . "\n");
}
// 性能基准测试
function benchmark(callable , int = 1000): float
{
= hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$fn();
}
return (hrtime(true) - $start) / 1e9;
}日志记录实践
php
<?php
declare(strict_types=1);
/**
* 简易日志记录器
*/
class SimpleLogger
{
private string $logFile;
private string $level = 'INFO';
public function __construct(string $logFile)
{
$this->logFile = $logFile;
}
public function info(string $message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
private function log(string $level, string $message, array $context): void
{
$timestamp = date('Y-m-d H:i:s');
$contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
}
}配置与环境检测
php
<?php
declare(strict_types=1);
// 环境检测工具
class EnvironmentChecker
{
public static function checkRequirements(array $requirements): array
{
$results = [];
foreach ($requirements as $name => $check) {
$results[$name] = is_callable($check) ? $check() : false;
}
return $results;
}
public static function getSystemInfo(): array
{
return [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'sapi' => PHP_SAPI,
'memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time'),
'loaded_extensions' => get_loaded_extensions(),
];
}
}常见问题排查
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| 连接超时 | 网络问题/配置错误 | 检查配置,增加超时时间 |
| 权限不足 | 文件/目录权限 | 使用 chmod/chown 修正 |
| 性能下降 | 索引缺失/数据量大 | 添加索引,优化查询 |
| 数据不一致 | 并发冲突/事务残留 | 使用锁机制和事务 |
| 内存溢出 | 大数据集/未释放资源 | 增大内存限制,分批处理 |
故障排除步骤
- 检查错误日志和异常信息
- 确认配置和环境是否正确
- 使用调试工具逐步排查
- 参考官方文档查找已知问题
版本兼容性说明
| 功能 | 最低版本 | 说明 |
|---|---|---|
| 基础功能 | PHP 8.1 | 本文档基准版本 |
| 只读属性 | PHP 8.1 | public readonly 修饰符 |
| 枚举类型 | PHP 8.1 | enum 类型和 match 表达式 |
| Fiber | PHP 8.1 | 协程/轻量级并发 |
| 命名参数 | PHP 8.0 | foo(arg_name: value) |
| 联合类型 | PHP 8.0 | `int |
| Null 安全运算符 | PHP 8.0 | $obj?->method() |
| 析构器 promotion | PHP 8.0 | __construct(public $x) |
php
<?php
declare(strict_types=1);
// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
if (version_compare(PHP_VERSION, $minVersion, '<')) {
throw new RuntimeException(
sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
);
}
}
ensureVersion('8.1.0');