gpt4 book ai didi

php - 此备份脚本中的 "drop table"和 "create table"选项有什么作用?

转载 作者:行者123 更新时间:2023-11-29 08:28:49 24 4
gpt4 key购买 nike

我需要一个脚本来备份我没有 cpanel、shell 或 phpmyadmin 访问权限的 MYSQL 数据库。

我只是关心这个脚本的DROP TABLE部分以及为什么需要它。我根本不想修改数据库,我只想备份。

这是我的代码:

backup_tables('localhost','username','password','blog');


/* backup the db OR just a table */
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);
}

最佳答案

因此,此脚本将生成一个文件,其中包含重新创建当前数据库的所有 SQL 命令。

因此,一旦脚本执行完毕,您就可以“导入”它在 phpmyadmin 中创建的文件,如果存在表,它将删除表,然后插入备份时表中的所有数据。

它不会修改当前数据库中的任何内容

例如,这是 phpmyadmin 中的“导出”函数将为测试表创建的内容:

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `test_table`
--

DROP TABLE IF EXISTS `test_table`;
CREATE TABLE IF NOT EXISTS `test_table` (
`id` int(11) NOT NULL,
`num` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `test_table`
--

INSERT INTO `test_table` (`id`, `num`) VALUES
(1, 23),
(2, 45);

只是一系列 SQL 语句来重新创建数据库。

关于php - 此备份脚本中的 "drop table"和 "create table"选项有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17227089/

24 4 0