Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export mysql table into SQL format? [closed]

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.

However I found the code below :

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);
}

It outputs the following error :

Notice: Undefined variable: return

and

Deprecated: Function ereg_replace() is deprecated

All I want is to export a SINGLE table via PHP into .sql format !....I'm not that familiar with PHP, but hope you can help me out !

like image 648
Ali Hamra Avatar asked Jun 10 '13 15:06

Ali Hamra


2 Answers

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");

You may want to check the contents of $result afterwads, to make sure everything went smooth.

Reference manual here.

like image 59
RandomSeed Avatar answered Sep 16 '22 14:09

RandomSeed


You are getting the error because you are using a deprecated function ereg_replace

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

I would suggest you to use preg_replace() as alternative to this function.

like image 41
Fabio Avatar answered Sep 17 '22 14:09

Fabio