
本文详解 CodeIgniter 使用 MySQLi 驱动时数据库备份失败的问题根源,通过重写 mysqli_utility.php 中的 _backup() 方法,实现兼容、稳定、可执行的 SQL 备份导出功能。
本文详解 codeigniter 使用 mysqli 驱动时数据库备份失败的问题根源,通过重写 `mysqli_utility.php` 中的 `_backup()` 方法,实现兼容、稳定、可执行的 sql 备份导出功能。
CodeIgniter 原生的数据库备份功能($this->dbutil->backup())在较新版本的 MySQLi 驱动下默认不可用,原因在于其 mysqli_utility.php 中的 _backup() 方法被直接置为“未实现”状态,并抛出 Unsupported feature of the database platform you are using 错误。该方法在底层仍保留逻辑框架,但关键部分被注释或禁用,且存在过时的 MySQL 扩展调用(如 mysql_field_type),导致与现代 mysqli 不兼容。
✅ 正确解决方案:安全重写 _backup() 方法
请按以下步骤操作(务必先备份原始文件):
打开文件:
system/database/drivers/mysqli/mysqli_utility.php定位并完全替换 _backup() 方法(约第 80 行起),使用以下已修正、兼容 PHP 7.4+ 及 MySQLi 的完整实现:
/**
* MySQLi Export
*
* @access private
* @param array Preferences
* @return string SQL backup content or FALSE on failure
*/
function _backup($params = array())
{
if (empty($params) || !is_array($params)) {
return FALSE;
}
extract($params);
$newline = "\n";
$output = '';
// Normalize tables list
$tables = isset($tables) ? (array) $tables : $this->db->list_tables();
$ignore = isset($ignore) ? (array) $ignore : array();
foreach ($tables as $table) {
if (in_array($table, $ignore, TRUE)) {
continue;
}
// Get CREATE TABLE statement
$query = $this->db->query("SHOW CREATE TABLE `" . $this->db->database . "`.`" . $table . "`");
if ($query === FALSE) {
continue;
}
$result = $query->row();
if (!$result) continue;
$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
if (!empty($add_drop) && $add_drop === TRUE) {
$output .= 'DROP TABLE IF EXISTS `' . $table . '`;'.$newline.$newline;
}
$output .= $result->{'Create Table'} . ';' . $newline . $newline;
// Skip data if not requested
if (empty($add_insert) || $add_insert !== TRUE) {
continue;
}
// Fetch all rows
$data_query = $this->db->query("SELECT * FROM `" . $table . "`");
if ($data_query->num_rows() === 0) {
continue;
}
// Analyze field types
$fields = $data_query->list_fields();
$field_count = count($fields);
$is_int = array_fill(0, $field_count, FALSE);
$field_names = array();
for ($i = 0; $i field_data()[$i];
$type = strtolower($field->type);
$is_int[$i] = in_array($type, ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'], TRUE);
$field_names[] = '`' . $field->name . '`';
}
$field_str = implode(', ', $field_names);
// Build INSERT statements
foreach ($data_query->result_array() as $row) {
$values = array();
foreach ($row as $key => $val) {
$idx = array_search($key, $fields, TRUE);
if ($val === NULL) {
$values[] = 'NULL';
} elseif ($is_int[$idx] === TRUE) {
$values[] = $val;
} else {
$values[] = $this->db->escape($val);
}
}
$output .= 'INSERT INTO `' . $table . '` (' . $field_str . ') VALUES (' . implode(', ', $values) . ');' . $newline;
}
$output .= $newline;
}
return $output;
}
⚠️ 注意事项与最佳实践
- 不要修改核心文件以外的逻辑:避免在控制器中自行拼接 SQL 或调用 mysqli_* 函数,应严格依赖 CI 的 DB 类封装。
- 备份路径权限:确保 assets/db_backup/ 目录存在且 Web 服务器有写入权限(Linux 下建议 chmod 755,Windows 下确认 IIS/Apache 用户可写)。
- 大库慎用:该方案适用于中小型数据库(
-
安全性增强(推荐):
- 备份文件名添加随机哈希或 Token,防止枚举下载;
- 限制备份路由仅限管理员访问(配合 $this->auth->is_admin() 等鉴权);
- 导出后自动清理临时文件(尤其 ZIP 生成时需注意内存占用)。
✅ 最终调用示例(控制器)
public function backup_db()
{
$this->load->dbutil();
$this->load->helper('file');
$this->load->helper('download');
$prefs = array(
'format' => 'txt', // 改用 'txt' 更稳妥(ZIP 需额外处理压缩)
'filename' => 'my_db_backup.sql',
'add_drop' => TRUE,
'add_insert' => TRUE,
'newline' => "\n"
);
$backup = $this->dbutil->backup($prefs);
if ($backup === FALSE) {
show_error('Database backup failed.');
return;
}
$filename = 'backup-on-' . date('Y-m-d-H-i-s') . '.sql';
$filepath = WRITEPATH . 'backups/' . $filename; // 推荐写入 writeable 目录而非 assets/
if (!write_file($filepath, $backup)) {
show_error('Unable to write backup file.');
return;
}
force_download($filename, $backup);
}
? 提示:若需 ZIP 压缩,请在生成 .sql 后使用 PHP 的 ZipArchive 类打包,而非依赖 CI 内置 ZIP(其对 mysqli 的支持不完善)。这样既保持兼容性,又提升健壮性。
至此,CodeIgniter 在 MySQLi 驱动下的数据库备份功能即可稳定运行,无需更换驱动或降级环境。











