我希望将整个数据库导出到PHP文件中的字符串(例如PHPmyadmin执行导出)。我想在那个时刻导出我所连接的数据库。
我无法通过Google找到明确的答案,只有很多人想要导出到CSV和其他东西。我只想要导出查询。
这甚至可能吗?如果是这样,怎么样?
答案 0 :(得分:2)
$dump = shell_exec('mysqldump --user=user --password=asdasd --host=localhost db_name');
或者你可以使用mysqldump的php实现,可以在https://github.com/clouddueling/mysqldump-php
上找到答案 1 :(得分:0)
您需要编写一个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);
答案 2 :(得分:0)
看看here!它是用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
);