我尝试了以下代码将 mysql 数据库备份到文件中,它完美地创建了我需要的 .sql 文件。
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;
}
但它显示错误代码:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: return
Filename: models/vote_m.php
有人可以告诉我如何解决这个问题吗?
最佳答案
第一次到达这条线时;
$return.= 'DROP TABLE '.$table.';';
...$return
没有可附加的值。要消除警告,您需要在开始循环之前初始化 $return
(可能为空字符串)。
关于php - 备份sql数据库出错但创建数据库转储文件成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008091/