0

I tried this following code to backup mysql database into file and it works perfectly create the .sql file I need.

function backup_tables()
{

$host='localhost';
$user='root';
$pass='';
$name='evote';
$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
$sql_name='db-backup.sql';
$handle = fopen($sql_name,'w+');
fwrite($handle,$return);
fclose($handle);

return $sql_name;
}

but it shows the error code :

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: return

Filename: models/vote_m.php

can somebody tell me how to fix this?

1 Answer 1

1

The first time you reach this line;

$return.= 'DROP TABLE '.$table.';';

...$return has no value to append to. To get rid of the warning, you'll need to initialize $return (to an empty string probably) before starting the loop.

Sign up to request clarification or add additional context in comments.

2 Comments

when I set $return='' before that line, the database doesn't completely backup. it's just have one table in the .sql file.
@user2467703 That's why I said before starting the loop (aka before the foreach line) :) If you put it inside the foreach, it will clear it out every iteration instead of just once at the start of the program as intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.