Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer

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.

share|improve this answer
when I set $return='' before that line, the database doesn't completely backup. it's just have one table in the .sql file. – user2467703 18 hours ago
@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. – Joachim Isaksson 18 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.