我已经使用db_backup
PongoCMS 的功能来备份 MySQL 数据库。几乎所有数据库表中的所有列都正确导出,但在使用“utf8”编码的表列上(我使用utf8_unicode_ci
了排序规则),这些列的导出数据填充有问号。
以下是我使用的功能:
public static function db_backup()
{
$type_db = Config::get('database.default');
$connections = Config::get('database.connections');
switch($type_db) {
case 'sqlite':
$file_name = $connections[$type_db]['database'] . '.' . $connections[$type_db]['driver'];
break;
case 'mysql':
$link = mysql_connect($connections[$type_db]['host'],$connections[$type_db]['username'],$connections[$type_db]['password']);
mysql_select_db($connections[$type_db]['database'],$link);
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
//Set time now
$now = date('Y-m-d-H-i-s');
//File header
$return ="### DB BACKUP: " . $connections[$type_db]['database'] . " at " . $now . " ###\n\n\n";
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE IF EXISTS '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "\n\n".$row2[1].";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#\n#i","\\n",$row[$j]);
if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");\n";
}
}
$return.="\n\n\n";
}
//save file
$file_name = 'db-backup-'.$now.'.sql';
$handle = fopen(path('storage') . 'database/' . $file_name, 'w+');
fwrite($handle, utf8_encode($return));
fclose($handle);
}
return $file_name;
}
但是,如果我从中导出数据库phpmyadmin
,则数据库会正确导出。应该在上述函数中更改/添加什么,以便该函数也正确导出数据库?