oa credit system tray rental -php database backup, restore,

  1. mydb.php // DB class
  2. backup.php // backup script
  3. restore.php // restore script
    4.OA credit tray erecting q <319.135.503.1>
    mydb.php

<?
class db{

var $ linkid;
var $ sqlid;
var $ record;

function db($host="",$username="",$password="",$database="")
{
if(!$this->linkid) @$this->linkid = mysql_connect($host, $username, $password) or die("连接服务器失败.");
@mysql_select_db($database,$this->linkid) or die("无法打开数据库");
return $this->linkid;}

function query($sql)
{if($this->sqlid=mysql_query($sql,$this->linkid)) return $this->sqlid;
else {
$this->err_report($sql,mysql_error);
return false;}
}

function nr($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
return mysql_num_rows($sql_id);}

function nf($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
return mysql_num_fields($sql_id);}

function nextrecord($sql_id="")
{if(!$sql_id) $sql_id=$this->sqlid;
if($this->record=mysql_fetch_array($sql_id)) return $this->record;
else return false;
}

function f($name)
{
if($this->record[$name]) return $this->record[$name];
else return false;
}

function close() {mysql_close($this->linkid);}

function lock($tblname,$op="WRITE")
{if(mysql_query("lock tables ".$tblname." ".$op)) return true; else return false;}

function unlock()
{if(mysql_query("unlock tables")) return true; else return false;}

function ar() {
return @mysql_affected_rows($this->linkid);
}

function i_id() {
return mysql_insert_id();
}

err_report function ($ SQL, $ ERR)
{
echo "Mysql query error <br>";
echo "query:." $ SQL "<br>";.
echo "error message:." $ ERR;
}
/ ** ** class ended * * /
}?>

backup.php

<?
error_reporting(E_ALL & ~ E_NOTICE);
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$mysqlhost="localhost"; //host name
$mysqluser="root"; //login name
$mysqlpwd=""; //password
$mysqldb=""; //name of database

the include ( "mydb.php");
$ D = new new DB (mysqlhost $, $ mysqluser, mysqlpwd $, $ MySQLdb);
/ -------------- interface ------ -------- / IF (! $ _ the POST [ 'ACT']) {/ ---------------------- /
$ Msgs [] = "server backup directory backup";
$ Msgs [] = 'for larger data tables, it is strongly recommended to use sub-volume backup ";
$ Msgs [] =" only select the backup to the server, you can use sub-volume backup ";
show_msg ($ Msgs);
?>
<form name = "Form1" Method = "POST" Action = "backup.php">
<Table width = "99%" border = ". 1" cellpadding = '0' cellspacing = '. 1' >
<TR align = left = "Center" class = 'header'> <TD colspan = "2"> data backup </ td> </ TR>
<TR> <TD colspan = "2"> backup </ td> < / tr>
<tr> <td> <input type = "radio" name = "bfzl" value = "quanbubiao"> backup all data </ td> <td> backup all the data in the data table into a backup file </ td> < / tr>
<tr> <td> <input type = "radio" name = "bfzl" value = "danbiao"> single table backup data
<select name = "tablename"> <option value = ""> select </ option>
<?
$ D-> Query ( "Show Status Table MySQLdb from $");
the while ($ D-> NextRecord ()) {
'. $ D-> F. echo "<Option value =" (' the Name ') " '. "(the Name'). $ D-> F"> '</ Option> ";}
?>
</ sELECT> </ TD> <TD> backup data in the selected data table into a separate backup file </ TD> </ TR>
<TR> <TD colspan = "2"> using sub-volume backup </ TD> </ TR>
<TR> <TD colspan = "2"> <INPUT type = "CheckBox" name = " fenjuan "value =" yes ">
sub-volume backup <input name ="filesize" type="text" size="10">K</td></tr>
<tr><td colspan="2">选择目标位置</td></tr>
<tr><td colspan="2"><input type="radio" name="weizhi" value="server" checked>备份到服务器</td></tr><tr class="cells"><td colspan='2'> <input type="radio" name="weizhi" value="localpc">cells"><td colspan='2'> <input type="radio" name="weizhi" value="localpc">cells"><td colspan='2'> <input type="radio" name="weizhi" value="localpc">
Backup to the local </ TD> </ TR>
<TR> <TD colspan = "2" align = left = 'Center'> <INPUT type = "Submit" name = "ACT" value = "backup"> </ td> < / TR>
</ Table> </ form>
<? / end interface ------------- ------------- /} / ----- ---------------------------- /
/ ---- / the else {/ ----------------------- - main ----------------------------------------- /
IF ($ _ POST [ 'weizhi'] == "localpc" && the POST $ _ [ 'fenjuan'] == 'Yes')
{$ Msgs [] = "only to select the backup server to use the sub-volume backup";
show_msg ($ Msgs) ; PageEnd ();}
IF ($ _ the POST [ 'fenjuan'] == "Yes" && the POST $ _ [ 'filesize']!)
{$ Msgs [] = "You choose the sub-volume backup, but did not complete the sub-volume File Size ";
show_msg ($ Msgs); PageEnd ();}
IF ($ _ POST [ 'weizhi'] ==" Server "&& writeable (!" ./ Backup "))
{$ Msgs [] =" backup file storage directory './backup' not write, edit the directory attribute ";
show_msg($msgs); pageend();}

/----------备份全部表-------------/if($_POST['bfzl']=="quanbubiao"){/----/
/----不分卷/if(!$_POST['fenjuan']){/--------------------------------/
if(!$tables=$d->query("show table status from $mysqldb"))
{$msgs[]="读数据库结构错误"; show_msg($msgs); pageend();}
$sql="";
while($d->nextrecord($tables))
{
$table=$d->f("Name");
$sql.=make_header($table);
$d->query("select from $table");
$num_fields=$d->nf();
while($d->nextrecord())
{$sql.=make_record($table,$num_fields);}
}
$filename=date("Ymd",time())."_all.sql";
IF ($ _ the POST [ 'weizhi'] == "localpc") down_file ($ SQL, $ filename);
ELSEIF ($ _ the POST [ 'weizhi'] == "Server")
{IF (write_file ($ SQL, $ filename) )
$ Msgs [] = "all data table data backup is complete, generating the backup file './backup/$filename'";
the else $ Msgs [] = "backup of all data tables failed";
show_msg ($ Msgs);
PageEnd () ;
}
/
----------------- not roll end /} / ----------------------- /
/
----------------- sub-volume / the else {/ ------------------------- /
IF ($ _ the POST [ 'filesize']!)
{$ Msgs [] = "Please fill in the backup file volume size"; show_msg ($ Msgs); PageEnd ();}
! IF ($ Tables = $ D-> Query ( "Show Status Table MySQLdb from $"))
{$ Msgs [] = "read errors database structure"; show_msg ($ msgs);pageend();}
$sql=""; $p=1;
$filename=date("Ymd",time())."_all";
while($d->nextrecord($tables))
{
$table=$d->f("Name");
$sql.=make_header($table);
$d->query("select
from $table");
$num_fields=$d->nf();
while($d->nextrecord())
{$sql.=make_record($table,$num_fields);
if(strlen($sql)>=$_POST['filesize']1000){
$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]="全部数据表-卷-".$p."-数据备份完成,生成备份文件'./backup/$filename'";
else $msgs[]="备份表-".$_POST['tablename']."-失败";
$p++;
$filename=date("Ymd",time())."_all";
$sql="";}
}
}
if($sql!=""){$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
.. $ msgs [] = "all data tables - Volume -" $ p "- Data backup is complete, generating the backup file './backup/$filename'";}
show_msg ($ Msgs);
/
------ --------------- end sub-volume /} / ----------------------------- --------- /
/
-------- all backup table end /} / ------------------------ --------------------- * /

/ -------- single table backup ------ / ELSEIF ($ _ the POST [ 'bfzl'] == "danbiao") {/ ----------------------- /
IF (! $ _ the POST [ 'TableName'])
{$ Msgs [] = "Please select the data to back up table"; show_msg ($ Msgs); PageEnd ();}
/ --------, regardless of volume / IF (! $ _ the POST [ 'fenjuan']) {/ ------------------------------- /
$ SQL = make_header ( _POST $ [ 'TableName']);
$ D-> Query ( "SELECT from" $ _ the POST [ 'TableName']);.
$ $ num_fields = D-> NF ();
the while ($ D-> NextRecord ())
{. $ SQL = make_record ($ _ the POST [ 'TableName'], $ NUM Fields);}
$ filename = DATE ( "Ymd", Time ()). "
" $ _ the POST [ 'TableName'].. "SQL." ;
IF ($ _ the POST [ 'weizhi']=="localpc") down_file($sql,$filename);
elseif($_POST['weizhi']=="server")
IF {(write_file (SQL $, $ filename))
$ Msgs [] = "Table -" $ _ POST [ 'tablename '] "- Data backup is complete, generating the backup file './backup/$filename'";..
the else $ msgs [] = "backup table -" $ _ POST [ 'tablename '] "- failed";..
show_msg ($ Msgs);
PageEnd ();
}
/
-------------- - Do not roll end /} / ------------------------------------ /
/
---- ------------ sub-volume / the else {/ -------------------------------- ------ /
IF (the POST $ _ [ 'filesize']!)
{$ Msgs [] = "Please fill in the backup file volume size"; show_msg ($ Msgs); PageEnd ();}
$ SQL = make_header ( $ the POST [ 'TableName']); P = $. 1;
$ = DATE filename ( "Ymd", Time ()). "
" $ _ the POST [ 'TableName'];.
$ D->
query("select from ".$_POST['tablename']);
$num_fields=$d->nf();
while ($d->nextrecord())
{
$sql.=make_record($_POST['tablename'],$num_fields);
if(strlen($sql)>=$_POST['filesize']1000){
$filename.=("_v".$p.".sql");
if(write_file($sql,$filename))
$msgs[]="表-".$_POST['tablename']."-卷-".$p."-数据备份完成,生成备份文件'./backup/$filename'";
else $msgs[]="备份表-".$POST['tablename']."-失败";
$p++;
$filename=date("Ymd",time())."
".$_POST['tablename'];
$sql="";}
}
if($sql!=""){$filename.=("_v".$p.".sql");
if(write_file($sql,filename $))


---------- end of the sub-volume/show_msg ($ Msgs);Volume -" $ p "- Data backup is complete, generating the backup file './backup/$filename'"; }.... $ Msgs [] = "Table -" $ _ POST [ 'tablename/} / ----------------------------------------------- --- /
/
---------- end single table backup /} / ---------------------------- ------------------ * /

/ --- /} / ------------- --------------------------- End of main program --------------- /

function write_file($sql,$filename)
{
$re=true;
if(!@$fp=fopen("./backup/".$filename,"w+")) {$re=false; echo "failed to open target file";}
if(!@fwrite($fp,$sql)) {$re=false; echo "failed to write file";}
if(!@fclose($fp)) {$re=false; echo "failed to close target file";}
return $re;
}

function down_file($sql,$filename)
{
ob_end_clean();
header("Content-Encoding: none");
header("Content-Type: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'application/octetstream' : 'application/octet-stream'));

header("Content-Disposition: ".(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? 'inline; ' : 'attachment; ')."filename=".$filename);

header("Content-Length: ".strlen($sql));
header("Pragma: no-cache");

header("Expires: 0");
echo $sql;
$e=ob_get_contents();
ob_end_clean();
}

function writeable($dir)
{

if (! is_dir ($ dir)) {
@mkdir ($ dir, 0777);
}

if(is_dir($dir))
{

if($fp = @fopen("$dir/test.test", 'w'))br/>{
@fclose($fp);
@unlink("$dir/test.test");
$writeable = 1;
}
else {
$writeable = 0;
}

}

return $writeable;

}

function make_header($table)
{global $d;
$sql="DROP TABLE IF EXISTS ".$table."\n";
$d->query("show create table ".$table);
$d->nextrecord();
$tmp=preg_replace("/\n/","",$d->f("Create Table"));
$sql.=$tmp."\n";
return $sql;
}

function make_record($table,$num_fields)
{global $d;
$comma="";
$sql .= "INSERT INTO ".$table." VALUES(";
for($i = 0; $i < $num_fields; $i++)
{$sql .= ($comma."'".mysql_escape_string($d->record[$i])."'"); $comma = ",";}
$sql .= ")\n";
return $sql;
}

function show_msg($msgs)
{
$title="提示:";
echo "<table width='100%' border='1' cellpadding='0' cellspacing='1'>";
echo "<tr><td>".$title."</td></tr>";
echo "<tr><td><br><ul>";
while (list($k,$v)=each($msgs))
{
echo "<li>".$v."</li>";
}
echo "</ul></td></tr></table>";
}

function pageend()
{
exit();
}
?>

restore.php

<?
error_reporting(E_ALL & ~ E_NOTICE);
session_start();
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$mysqlhost="localhost"; //host name
$mysqluser="root"; //login name
$mysqlpwd=""; //password
$mysqldb=""; //name of database

include("mydb.php");
$d=new db($mysqlhost,$mysqluser,$mysqlpwd,$mysqldb);

/ ** interface * / IF (! $ _ The POST [ 'ACT'] &&! $ _ The SESSION [ 'data_file']) {/ * /
$ Msgs [] = "This function while restoring the backup data, will cover all of the original data, determine whether a resumption avoid data loss ";
$ Msgs [] =" data recovery can only be restored by dShop exported data files, other software export format may not be recognized ";
$ Msgs [] =" from local data recovery requires the server to support file upload and ensure that the data size is less than the maximum allowed upload it can use to recover from server ";
$ Msgs [] =" If you use sub-volume backup, simply import the file manually volume 1, other data file is imported automatically by the system ";
show_msg ($ Msgs);
?>
<form Action =" "Method =" POST "the enctype =" multipart / form-data "name =" the restore.php ">
<width = Table" % 91 is "border =" 0 "cellpadding =" 0 "cellspacing =". 1 ">
<TR align = left =" Center "class =" header "> <TD colspan =" 2 "align = left =" Center "> data recovery </td></tr>
<tr><td width="33%"><input type="radio" name="restorefrom" value="server" checked>
从服务器文件恢复 </td><td width="67%"><select name="serverfile">
<option value="">-请选择-</option>
<?
$handle=opendir('./backup');
while ($file = readdir($handle)) {
if(pregmatch("/^[0-9]{8,8}([0-9a-z]+)(.sql)$/",$file)) echo "<option value='$file'>$file</option>";}
closedir($handle);
?>
</select> </td></tr>
<tr><td><input type="radio" name="restorefrom" value="localpc"> 从本地文件恢复</td>
<td><input type="hidden" name="MAX_FILE_SIZE" value="1500000"><input type="file" name="myfile"></td></tr>
<tr><td colspan="2" align="center"> <input type="submit" name="act" value="恢复"></td> </tr></table></form>

<? / ** interface End * /} / * * /
/ **** main routine * / if ($ _ POST [ 'act'] == " Recovery") {/
/
/ Server Recovery / if ($ _ POST [ 'restorefrom'] == "server") {/ /
IF ($ _ POST [ 'serverfile'])!
{$ Msgs [] = "you choose to restore a backup from a server file, but does not specify the backup file";
show_msg ($ Msgs); PageEnd ();}
! IF (the preg_match ( "/ _ V [0-9] + /", the POST $ _ [ 'serverfile']))
{$ filename = "./ Backup /".$_ the POST [ 'serverfile '];
. IF (import ($ filename)) $ Msgs [] = "backup file" $ _ POST [' serverfile ' .] " successfully imported database";
. the else $ Msgs [] = "backup file" $ _ POST [' . serverfile '] "import failed";
show_msg ($ Msgs); PageEnd ();
}
else
{
$filename="./backup/".$_POST['serverfile'];
.. if (import ($ filename )) $ msgs [] = " backup file" $ _ POST [ 'serverfile' ] " Successfully imported database";
. the else {$ Msgs [] = "backup file" $ _ POST [ 'serverfile' .] "import failed"; show_msg ($ Msgs); PageEnd ();}
$ voltmp = the explode ( "_ V", $ _ the POST [ 'serverfile']);
$ volname = $ voltmp [0];
$ volnum = the explode ( ".sq", $ voltmp [. 1]);
$ volnum = the intval ($ volnum [0]) +. 1;
. $ tmpfile = $ volname "_ V" $ volnum.. "SQL.";
IF (the file_exists (. " /backup/".$tmpfile))
{
$ Msgs [] =. "starts automatically introduced into this sub-volume backup after 3 seconds, the next section: file" $ tmpfile ", do not stop the program manually. operation, in order to avoid damage to the structure of the database ";
$ _SESSION [ 'data_file'] = $ tmpfile;
show_msg ($ Msgs);
SLEEP (. 3);
echo" <Script Language = 'JavaScript'> ";
echo"= LOCATION 'the restore.php'; ";
echo" </ Script> ";
}
the else
{
$ Msgs [] =" Import All this sub-volume backup success ";
show_msg ($ Msgs);
}
}
/ ** server back end * /} / **** /
/ ** local recovery / IF (the POST $ _ [ 'restorefrom'] == "localpc") {/ /
Switch ($ _FILES [ 'myfile'] [ 'error'])
{
Case. 1:
Case 2:
$ Msgs [] = "your uploaded file is larger than the server defined value, upload unsuccessful";
BREAK;
Case. 3:
$ Msgs [] = " failed to upload files from local full backup ";
BREAK;
Case. 4:
$ Msgs [] =" failed to upload files from local backup ";
BREAK;
Case 0:
BREAK;
}
IF ($ Msgs) Show { MSG ($ Msgs); PageEnd ();}
$ = DATE fname ( "Ymd", Time ()). "
" .sjs (. 5). "SQL";.
IF (entries for is_uploaded_file ($ _ the FILES [ 'myfile']['tmp_name'])) {
copy($_FILES['myfile']['tmp_name'], "./backup/".$fname);}

IF (the file_exists ( "./ Backup /".$ fname))
{
$ Msgs [] =" local backup files uploaded successfully ";
IF (Import (" ./ Backup /".$ fname)) {$ Msgs [] = "local database backup file successfully imported"; the unlink ( "./ backup /".$ fname);}
the else $ Msgs [] =" local backup files into a database failed ";
}
the else ($ Msgs [] =" upload from the local backup file failed ");
show_msg ($ Msgs);
/ local recovery end * /} / **** /
/ **** end main program * /} / **
/
/ * remaining volume backup min * /
IF (! $ _ the POST [ 'ACT'] && $ _ the SESSION [ 'data_file'])
{
$ filename = "./ Backup /".$_ the SESSION [ 'data_file'];
IF (Import ($ filename)) $ Msgs [] = "backup file" $ _ SESSION [ 'data_file' ] " database successfully imported.";
else {. $ msgs [] = " backup file" $ _ SESSION [ 'data_file' ] " import failed";. show_msg ($ msgs) ; pageend ();}
$ voltmp = the explode ( "_ V", $ _ the SESSION [ 'data_file']);
$ volname = $ voltmp [0];
$ volnum = the explode (. "sq.", $ voltmp [. 1]);
$ volnum = the intval ($ volnum [0]) +. 1;
. $ $ volname tmpfile = "_ V" $ volnum "SQL.";..
IF (the file_exists ( "./ Backup /".$ tmpfile))
{
$ Msgs [] =" program start automatically import the backup sub-volume after 3 seconds, the next section: the file. "$ tmpfile.", do not run manually stop the program, so as to avoid damage to the structure of the database ";
$ _SESSION [ 'data_file'] = $ tmpfile;
show_msg ($ Msgs);
SLEEP (. 3);
echo "<Script Language = 'JavaScript'>";
echo "LOCATION = 'the restore.php';";
echo "</ Script>";
}
the else
{
$ Msgs [] = "this sub-volume backup all successfully introduced";
the unset ($ _ the SESSION [ 'data_file']);
show_msg ($ Msgs);
}
}
/ ** remaining end volume backup min * **
/
function import($fname)
{global $d;
$sqls=file($fname);
foreach($sqls as $sql)
{
str_replace("\r","",$sql);
str_replace("\n","",$sql);
if(!$d->query(trim($sql))) return false;
}
return true;
}
function show_msg($msgs)
{
$title="提示:";
echo "<table width='100%' border='1' cellpadding='0' cellspacing='1'>";
echo "<tr><td>".$title."</td></tr>";
echo "<tr><td><br><ul>";
while (list($k,$v)=each($msgs))
{
echo "<li>".$v."</li>";
}
echo "</ul></td></tr></table>";
}

function pageend()
{
exit();
}
?>

File structure is very clear, as long as the database server set up in the file 2 and 3 which address, user name, password, you can backup and restore the data. have to be aware of is:

Use the time to build a Backup directory under the same directory permissions need to be written, and to export the script.
• When the database backup is relatively large, the server script timeout to transfer larger.
Support for sub-volume backup and restore time as long as the selected sub-volume backup first script will automatically restore all the scripts.
· Sub-volume file size is not too large, preferably not more than 2MB.
· Safety reasons, do not have time to remember to remove the script from the server.

Database backup
principle 1.php backup of the database
to find all tables to find all the fields to find all the data generated SQL
2.php in mysql related functions
mysql_list_tables () function table query, similar to the mysql_query () function
mysql_fetch_field () field information function that returns a handle to
the Name field the name of the
name of the database field belongs Table
type type field of
the maximum length of the field max_length
whether not_null field is blank
3. backup precautions
a. Note that the size of the database, too large or too much fragmentation process
b. the generated SQL file name or there is not already guessed
c generated backup file can be saved as a table unit or automatically.
D ZIP assembly may be used to save the generated compressed file.
$ dbname = "the root"
mysql_connect ( 'localhost', 'the root', '');
the mysql_select_db ();
$ TQ = mysql_list_tables ($ dbname);
the while ($ mysql_fetch_rows TR = ($ TQ)) {

}
function get_table_fd($dbname){
$query=mysql_query("select * from $dbname");
while($row=mysql_fetch_field($query)){
echo $row->name
}
}

Guess you like

Origin blog.51cto.com/14524882/2434601