php - 将mysql表导出成SQL格式?

标签 php mysql database backup

<分区>

是否可以通过 PHP 代码将包含记录的表导出为 SQL 格式?我一直在四处寻找,我发现的只是将其导出为 CSV 文件。

但是我找到了下面的代码:

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 将单个表导出为 .sql 格式!....我对 PHP 不是很熟悉,但希望你能帮助我!

最佳答案

不要重新发明轮子。您需要的几乎是开箱即用的:

<?php
    $result = exec("/path/to/mysqldump -u$username -p$password your_database your_table > /desired/output/path/dump.sql");

之后您可能需要检查 $result 的内容,以确保一切顺利。

Reference manual here.

关于php - 将mysql表导出成SQL格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027980/

相关文章:

php - 如何根据起始IP和网络掩码长度计算范围内的结束IP

php - 如何在一个sql查询中连接两个表?

使用 use 或 namespace 语句时出现 php 语法错误 : unexpected '/' ,

php - 动态链接中无用的获取变量以改善 SEO

php - 如何在 MySQLi 语句中插入变量?

php - 在给定时间后自动终止 Linux 进程/php 脚本

mysql查询根据两条数据显示输出

mysql - 在 mysql 中使用 Sum (if) 的列总计

database - 如何在 symfony2 上处理没有实体的表?

python - 当字符串字段的一部分相同时,Mongodb 文本索引重复键错误