我希望将我的整个数据库导出到PHP文件中的字符串(例如PHPmyadmin执行导出)。我想导出此时连接到的数据库。
我真的无法通过谷歌找到确切的答案,只是很多人想导出到CSV之类的东西。我只想要导出查询。
这有可能吗?如果是,如何?
$dump = shell_exec('mysqldump --user=user --password=asdasd --host=localhost db_name');
或者,您可以使用mysqldump的php实现,在https://github.com/clouddueling/mysqldump-php
您需要编写一个PHP函数,帮助您将所有MySQL数据导出到.sql文件中,稍后您可以使用gzip并保存
backup_tables('localhost','username','password', 'databasename');
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$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] = str_replace("'n","''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
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
链接-http://davidwalsh.name/backup-mysql-database-php
关于做gzip,你可以参考这个
// Name of the file we are compressing
$file = "test.txt";
// Name of the gz file we are creating
$gzfile = "test.gz";
// Open the gz file (w9 is the highest compression)
$fp = gzopen ($gzfile, 'w9');
// Compress the file
gzwrite ($fp, file_get_contents($file));
// Close the gz file and we are done
gzclose($fp);
链接-https://stackoverflow.com/a/6073415/2482430
看看这里!这是一个用php编写的本地解决方案。您不需要执行mysqldump,也不需要处理不完整的脚本。这是一个完整的mysqldump克隆。
您可以使用composer来安装它,或者只需下载php文件,它就像做一样简单
<?php
use Ifsnop'Mysqldump as IMysqldump;
try {
$dump = new IMysqldump'Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch ('Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
它支持高级用户,并从原始的mysqldump中复制了许多选项。
所有选项都在github页面上进行了解释,但或多或少都是自动解释的:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-keys' => true,
'where' => '',
'no-create-info' => false,
'skip-triggers' => false,
'add-drop-trigger' => true,
'hex-blob' => true,
'databases' => false,
'add-drop-database' => false,
'skip-tz-utc' => false
);