将mysql表导出为SQL格式? [英] Export mysql table into SQL format?
本文介绍了将mysql表导出为SQL格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以通过PHP代码将包含其记录的表导出为sql格式?
Is it possible to export a table with its records into sql format via php code ? I've been looking around and all i found is exporting it as csv file.
但我发现下面的代码:
backup_tables('localhost','root','','compare_db');
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] = ereg_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);
}
它会输出以下错误:
Notice: Undefined variable: return
Deprecated: Function ereg_replace() is deprecated
所有我想要的是通过PHP导出SINGLE表到.sql格式!...我不熟悉PHP,但希望你们帮助我! p>
All I want is to export a SINGLE table via PHP into .sql format !....I'm not that familiar with PHP, but hope you guys help me out !
推荐答案
不要重新发明轮子。您所需要的已经存在的几乎是现成的:
Do not reinvent the wheel. What you need already exists almost out-of-the-box:
<?php
$result = exec("/path/to/mysqldump -u$username -p$password your_database your_table > /desired/output/path/dump.sql");
您可能想检查 $ result
afterwads,以确保一切顺利。
You may want to check the contents of $result
afterwads, to make sure everything went smooth.
这篇关于将mysql表导出为SQL格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文