php定时备份数据库数据,导出sql文件

  1. <?php
  2. //无论客户端是否关闭浏览器,下面的代码都将得到执行。
  3. ignore_user_abort( true);set_time_limit( 0);
  4. //function write_txt(){
  5. ini_set( "max_execution_time", "180"); //避免数据量过大,导出不全的情况出现。
  6. $host= "127.0.0.1"; //数据库地址
  7. $dbname= "apiadmin"; //这里配置数据库名
  8. $username= "root"; //用户名
  9. $passw= "root"; //这里配置密码
  10. $filename=date( "Y-m-d_H-i-s"). "-".$dbname. ".sql";
  11. header( "Content-disposition:filename=".$filename); //所保存的文件名
  12. header( "Content-type:application/octetstream");
  13. header( "Pragma:no-cache");
  14. header( "Expires:0");
  15. //备份数据
  16. $i = 0;
  17. $crlf= "\r\n";
  18. global $dbconn;
  19. $dbconn = mysql_connect($host,$username,$passw); //数据库主机,用户名,密码
  20. $db = mysql_select_db($dbname,$dbconn);
  21. mysql_query( "SET NAMES 'utf8'");
  22. $tables =mysql_list_tables($dbname,$dbconn);
  23. $num_tables = @mysql_numrows($tables);
  24. print "-- filename=".$filename;
  25. while($i < $num_tables)
  26. {
  27. $table=mysql_tablename($tables,$i);
  28. print $crlf;
  29. echo get_table_structure($dbname, $table, $crlf). ";$crlf$crlf";
  30. //echo get_table_def($dbname, $table, $crlf).";$crlf$crlf";
  31. echo get_table_content($dbname, $table, $crlf);
  32. $i++;
  33. }
  34. //}
  35. function get_table_structure($db,$table,$crlf)
  36. {
  37. global $drop;
  38. $schema_create = "";
  39. if(! empty($drop)){ $schema_create .= "DROP TABLE IF EXISTS `$table`;$crlf";}
  40. $result =mysql_db_query($db, "SHOW CREATE TABLE $table");
  41. $row=mysql_fetch_array($result);
  42. $schema_create .= $crlf. "-- ".$row[ 0].$crlf;
  43. $schema_create .= $row[ 1].$crlf;
  44. Return $schema_create;
  45. }
  46. //获得表内容
  47. function get_table_content($db, $table, $crlf)
  48. {
  49. $schema_create = "";
  50. $temp = "";
  51. $result = mysql_db_query($db, "SELECT * FROM $table");
  52. $i = 0;
  53. while($row = mysql_fetch_row($result))
  54. {
  55. $schema_insert = "INSERT INTO `$table` VALUES (";
  56. for($j= 0; $j<mysql_num_fields($result);$j++)
  57. {
  58. if(! isset($row[$j]))
  59. $schema_insert .= " NULL,";
  60. elseif($row[$j] != "")
  61. $schema_insert .= " '".addslashes($row[$j]). "',";
  62. else
  63. $schema_insert .= " '',";
  64. }
  65. $schema_insert = ereg_replace( ",$", "",$schema_insert);
  66. $schema_insert .= ");$crlf";
  67. $temp = $temp.$schema_insert ;
  68. $i++;
  69. }
  70. return $temp;
  71. }
  72. //usleep适用于php5.0以上,定时
  73. function do_cron(){usleep( 1);write_txt();}
  74. while( 1){do_cron();}
  75. ?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值