mysql php数据打包备份程序

 更新时间:2016年11月25日 16:30  点击:1764

mysql php数据打包备份程序
 if (!$dbname) {
  $errmsg = 'Please input dbname';
 } else {
  dbconn($dbhost, $dbuser, $dbpass, $dbname, $charset, $dbport);
  if (!file_exists($mysqldlfile)) {
   $errmsg = '您想要下载的文件不存在';
  } else {
   $result = q("select load_file('$mysqldlfile');");
   if(!$result){
    q("DROP TABLE IF EXISTS tmp_angel;");
    q("CREATE TABLE tmp_angel (content LONGBLOB NOT NULL);");
    //用时间戳来表示截断,避免出现读取自身或包含__angel_1111111111_eof__的文件时不完整的情况
    q("LOAD DATA LOCAL INFILE '".addslashes($mysqldlfile)."' INTO TABLE tmp_angel FIELDS TERMINATED BY '__angel_{$timestamp}_eof__' ESCAPED BY '' LINES TERMINATED BY '__angel_{$timestamp}_eof__';");
    $result = q("select content from tmp_angel");
    q("DROP TABLE tmp_angel");
   }
   $row = @mysql_fetch_array($result);
   if (!$row) {
    $errmsg = 'Load file failed '.mysql_error();
   } else {
    $fileinfo = pathinfo($mysqldlfile);
    header('Content-type: application/x-'.$fileinfo['extension']);
    header('Content-Disposition: attachment; filename='.$fileinfo['basename']);
    header("Accept-Length: ".strlen($row[0]));
    echo $row[0];
    exit;
   }
  }
 }

php 重命名与复制文件
  $nname = $nowpath.$newfilename;
  if (file_exists($nname) || !file_exists($oldname)) {
   m($nname.' 目标文件已经存在或者原始文件不存在');
  } else {
   m(basename($oldname).' 重命名 '.basename($nname).(@rename($oldname,$nname) ? ' 成功' : '失败'));
  }
 }

 // 复制文件
 elseif ($sname && $tofile) {
  if (file_exists($tofile) || !file_exists($sname)) {
   m('目标文件已经存在或者原始文件不存在');
  } else {
   m(basename($tofile).' copied '.(@copy($sname,$tofile) ? basename($tofile).' 成功' : '失败'));
  }

使用一个很简单的表,mysql和oracle使用的表结构是一样的,都只有三个字段,结构如下:
mysql的表结构:
CREATE TABLE board (
   board_id smallint(6) NOT NULL auto_increment,
   board_name char(16) NOT NULL,
   board_manager char(20),
   PRIMARY KEY (board_id)
);
oracle的结构:
CREATE TABLE PHP_ORACLE."BOARD"
       ("BOARD_ID" FLOAT,
       "BOARD_NAME" CHAR(16) NOT NULL,
       "BOARD_MANAGER" CHAR(20)) ;

我们只测试了INSERT操作花的时间,对于select,并未作测试。
因为win32下只有PHP3才能连接oracle数据库,所以只测试了用PHP3连接oracle的性能。相
信在PHP4的正式版本出来后,用PHP4连接oracle的速度应该有所提升。
而在LINUX下,因为我没有装oracle,所以只测试了mysql的性能。据说在LINUX下,oracle
的性能不错,只是无法测试。
并且我们将所有的用于数据库连接和oracle用来分析sql语句的代码都放在了统计代码之外
,所以测试得出的时间只是用于执行SQL操作所花费的时间。

用来测试mysql的程序:

<?php
$dblink=mysql_connect("localhost","root","shh123");
mysql_select_db("bbs");
$counter=1;
set_time_limit(300);
$query="insert into board (board_name,board_manager) values (test,test)";
$begin_time=time();
for ($i=1;$i<=10000;$i++){
        mysql_db_query("bbs",$query);
    $counter++;
}
$end_time=time();
mysql_close($dblink);
echo "test db speed...<br>";
echo "begin time:".$begin_time."<BR>";
echo "<BR>end time:".$end_time."<BR>";
$total=$end_time-$begin_time;
echo "total spent time:".$total;
?>

用来测试oracle的程序:

<?php
$handle=OCILogon("php_oracle","php_oracle");

$counter=1;
set_time_limit(300);
$query="insert into board (board_id,board_name,board_manager) values (:board_id,test,test)";
$state=OCIParse($handle, $query);
OCIBindByName($state, ":board_id", &$i,32);
$begin_time=time();
for ($i=1;$i<=10000;$i++){
        ociexecute($state);
}
$end_time=time();
OCIFreeStatement($state);
ocilogoff($handle);
echo "test db speed...<br>";
echo "begin time:".$begin_time."<BR>";
echo "<BR>end time:".$end_time."<BR>";
$total=$end_time-$begin_time;
echo "total spent time:".$total;
?>

测试结果:

环境:win32+apache+php4+mysql
结果:28秒

环境:win32+apache+php3+mysql
结果:34秒

环境:win32+apache+php3+oracle8.0.5(oci函数)
结果:46秒

环境:linux+apache+php4+mysql
结果:10秒

结论:
在WIN32下,mysql的性能虽然不是很好,但和oracle8比起来,还是要快很多,尤其是我在
测试程序中,并没有将数据库连接的语句包括进来,所以这个测试结果只是插入数据所花费
的时间,而oracle的连接,天,太慢了!在我的机器上,连接一次,至少1-2秒钟。
而在LINUX下,mysql的性能相对于在WIN32下,又有了一个很大的飞跃。由28秒骤减到10秒。
所以,如果你不需要存储过程的支持,并且数据库量不是大的那么惊人的话,还是在LINUX
下使用mysql作为你的数据库吧!这个轻量级的数据库可以给你最佳的性能、可管理性和相
当不错的安全性。

php 文件在线压缩代码


class PHPZip
{
 function Zip($dir, $zipfilename)
 {
     if (@function_exists('gzcompress'))
  { 
   $curdir = getcwd();
   if (is_array($dir))
   {
     $filelist = $dir;
   }
   else
   {
    $filelist = $this -> GetFileList($dir);
   }
   
   if ((!empty($dir))&&(!is_array($dir))&&(file_exists

($dir))) chdir($dir);
   else chdir($curdir);

   if (count($filelist)>0)
   {
    foreach($filelist as $filename)
    {
     if (is_file($filename))
     {
      $fd = fopen ($filename,

"r");
      $content = @fread ($fd,

filesize ($filename));
      fclose ($fd);

      if (is_array($dir))

$filename = basename($filename);
      $this -> addFile($content,

$filename);
     }
    }
    $out = $this -> file();

    chdir($curdir);
    $fp = fopen($zipfilename, "w");
    fwrite($fp, $out, strlen($out));
    fclose($fp);
   }
   return 1;
  }
  else return 0;
 }

 function GetFileList($dir)
 {
  if (file_exists($dir))
  {
   $args = func_get_args();
   $pref = $args[1];
    
   $dh = opendir($dir);
   while($files = readdir($dh))
   {
    if (($files!=".")&&($files!=".."))
    {
     if (is_dir($dir.$files))
     {
      $curdir = getcwd();
      chdir($dir.$files);
      $file = array_merge($file,

$this -> GetFileList("", "$pref$files/"));
      chdir($curdir);
     }
     else $file[]=$pref.$files;
    }
   }
   closedir($dh);
  }
  return $file;
 }

    var $datasec      = array();
    var $ctrl_dir     = array();
    var $eof_ctrl_dir = "x50x4bx05x06x00x00x00x00";
    var $old_offset   = 0;

    /**
     * Converts an Unix timestamp to a four byte DOS date and time format

(date
     * in high two bytes, time in low two bytes allowing magnitude

comparison).
     *
     * @param  integer  the current Unix timestamp
     *
     * @return integer  the current date in a four byte DOS format
     *
     * @access private
     */
    function unix2DosTime($unixtime = 0) {
        $timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);

        if ($timearray['year'] < 1980) {
         $timearray['year']    = 1980;
         $timearray['mon']     = 1;
         $timearray['mday']    = 1;
         $timearray['hours']   = 0;
         $timearray['minutes'] = 0;
         $timearray['seconds'] = 0;
        } // end if

        return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] <<

21) | ($timearray['mday'] << 16) |
                ($timearray['hours'] << 11) | ($timearray['minutes'] << 5) |

($timearray['seconds'] >> 1);
    } // end of the 'unix2DosTime()' method


    /**
     * Adds "file" to archive
     *
     * @param  string   file contents
     * @param  string   name of the file in the archive (may contains the

path)
     * @param  integer  the current timestamp
     *
     * @access public
     */
    function addFile($data, $name, $time = 0)
    {
        $name     = str_replace('\', '/', $name);

        $dtime    = dechex($this->unix2DosTime($time));
        $hexdtime = 'x' . $dtime[6] . $dtime[7]
                  . 'x' . $dtime[4] . $dtime[5]
                  . 'x' . $dtime[2] . $dtime[3]
                  . 'x' . $dtime[0] . $dtime[1];
        eval('$hexdtime = "' . $hexdtime . '";');

        $fr   = "x50x4bx03x04";
        $fr   .= "x14x00";            // ver needed to extract
        $fr   .= "x00x00";            // gen purpose bit flag
        $fr   .= "x08x00";            // compression method
        $fr   .= $hexdtime;             // last mod time and date

        // "local file header" segment
        $unc_len = strlen($data);
        $crc     = crc32($data);
        $zdata   = gzcompress($data);
        $c_len   = strlen($zdata);
        $zdata   = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix

crc bug
        $fr      .= pack('V', $crc);             // crc32
        $fr      .= pack('V', $c_len);           // compressed filesize
        $fr      .= pack('V', $unc_len);         // uncompressed filesize
        $fr      .= pack('v', strlen($name));    // length of filename
        $fr      .= pack('v', 0);                // extra field length
        $fr      .= $name;

        // "file data" segment
        $fr .= $zdata;

        // "data descriptor" segment (optional but necessary if archive is

not
        // served as file)
        $fr .= pack('V', $crc);                 // crc32
        $fr .= pack('V', $c_len);               // compressed filesize
        $fr .= pack('V', $unc_len);             // uncompressed filesize

        // add this entry to array
        $this -> datasec[] = $fr;
        $new_offset        = strlen(implode('', $this->datasec));

        // now add to central directory record
        $cdrec = "x50x4bx01x02";
        $cdrec .= "x00x00";                // version made by
        $cdrec .= "x14x00";                // version needed to extract
        $cdrec .= "x00x00";                // gen purpose bit flag
        $cdrec .= "x08x00";                // compression method
        $cdrec .= $hexdtime;                 // last mod time & date
        $cdrec .= pack('V', $crc);           // crc32
        $cdrec .= pack('V', $c_len);         // compressed filesize
        $cdrec .= pack('V', $unc_len);       // uncompressed filesize
        $cdrec .= pack('v', strlen($name) ); // length of filename
        $cdrec .= pack('v', 0 );             // extra field length
        $cdrec .= pack('v', 0 );             // file comment length
        $cdrec .= pack('v', 0 );             // disk number start
        $cdrec .= pack('v', 0 );             // internal file attributes
        $cdrec .= pack('V', 32 );            // external file attributes -

'archive' bit set

        $cdrec .= pack('V', $this -> old_offset ); // relative offset of

local header
        $this -> old_offset = $new_offset;

        $cdrec .= $name;

        // optional extra field, file comment goes here
        // save to central directory
        $this -> ctrl_dir[] = $cdrec;
    } // end of the 'addFile()' method


    /**
     * Dumps out file
     *
     * @return  string  the zipped file
     *
     * @access public
     */
    function file()
    {
        $data    = implode('', $this -> datasec);
        $ctrldir = implode('', $this -> ctrl_dir);

        return
            $data .
            $ctrldir .
            $this -> eof_ctrl_dir .
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries

"on this disk"
            pack('v', sizeof($this -> ctrl_dir)) .  // total # of entries

overall
            pack('V', strlen($ctrldir)) .           // size of central dir
            pack('V', strlen($data)) .              // offset to start of

central dir
            "x00x00";                             // .zip file comment

length
    } // end of the 'file()' method


}

php 删除数据表与删除数据库


//---------------------------删除数据表
function Ebak_Drop($tablename,$dbname){
 global $empire;
 $dbname=RepPostVar($dbname);
 $empire->query("use `$dbname`");
 $count=count($tablename);
 if(empty($count))
 {printerror("EmptyChangeDelTb","history.go(-1)");}
 $a="";
 $first=1;
 for($i=0;$i<$count;$i++)
 {
  if(empty($first))
  {
   $a.=",";
     }
  else
  {
   $first=0;
  }
  $a.="`".$tablename[$i]."`";
    }
 $sql1=$empire->query("DROP TABLE IF EXISTS ".$a.";");
 printerror("DelTbSuccess","ChangeTable.php?mydbname=$dbname");
}

//--------------------------删除数据库
function Ebak_DropDb($dbname){
 global $empire;
 $dbname=RepPostVar($dbname);
 if(empty($dbname))
 {
  printerror("NotChangeDelDb","history.go(-1)");
 }
 $sql=$empire->query("DROP DATABASE `$dbname`");
 if($sql)
 {
  printerror("DelDbSuccess","ChangeDb.php");
 }
 else
 {printerror("DbError","history.go(-1)");}
}

[!--infotagslink--]

相关文章