php mysql数据的导入导出,数据表结构的导入导出

 更新时间:2016年11月25日 16:29  点击:1835

实现数据的导入导出,数据表结构的导入导出
********************************************************/

        //
        //包含Mysql数据库操作文件
        //
        require_once("MysqlDB.php");
        
/*******************************************************
**类    名:MysqlDB
**类 编 号:lcq-DB-003
**作    用:数据库链接的建立,数据操作,获取字段个数,记录条数等
**作    者:林超旗
**编写日期:(2007-04-07)
********************************************************/
class DBManagement implements IDBManagement
{        
        //
        //当前数据库中所有的数据表的名字
        //
        private $TablesName;
        //
        //默认路径
        //
        private $DefaultPath;
        //
        //当前要操作的数据库名
        //
        private $DatabaseName;
        //
        //操作数据库的对象
        //
        private $db;
        
/*******************************************************
**方 法 名:__construct
**功能描述:创建一个DBManagement的对象
**输入参数:$_DatabaseName-string<要操作的数据库名,如果为空则从配置文件中读取>
**        $_DefaultPath-string<存储数据的默认路径,如果为空则从配置文件中读取>
**输出参数:无
**返 回 值:无
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        function __construct($_DatabaseName="",$_DefaultPath="")//
        {
                require("config.inc.php");
                if(!$_DatabaseName)        {$this->DatabaseName=$dbName;}
                else {$this->DatabaseName=$_DatabaseName;}
               
                if(!$_DefaultPath) {$this->DefaultPath=$defaultPath;}
                else {$this->DefaultPath=$_DefaultPath;}
                $path=realpath($this->DefaultPath);
                $this->DefaultPath=str_replace("\","/",$path);
                //$this->db=new DBFactory();
                $this->db=new MysqlDB();
        }
        
/*******************************************************
**方 法 名:GetTablesName
**功能描述:获取$this->Database的所有数据表的名字
**输入参数:无         
**输出参数:无
**返 回 值:-array <$this->TablesName:$this->Database的所有数据表的名字>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function GetTablesName()
        {
                $result=$this->db->Query("show table status");
                while($Row=$this->db->NextRecord($result))
                {
                        $this->TablesName[]=$Row["Name"];
                }
                return $this->TablesName;
        }
        
/*******************************************************
**方 法 名:GetDataFileName
**功能描述:获取与$this->Database的所有数据表对应的数据文件的物理文件名
**输入参数:无         
**输出参数:无
**返 回 值:-array <$DataFilesName:$与$this->Database的所有数据表对应的数据文件的物理文件名>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function GetDataFileName()
        {
                $this->GetTablesName();
                $count=count($this->GetTablesName());
                for ($i=0;$i<$count;$i++)
                {
                        $DataFilesName[]=$this->DefaultPath."/".$this->TablesName[$i].".txt";
                        //echo $DataFilesName[$i];
                }
                return $DataFilesName;
        }
        
/*******************************************************
**方 法 名:SaveTableStructure
**功能描述:保存数据表的结构到install.sql文件中,目标路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示保存成功;
**                为false表示保存失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function SaveTableStructure($text)
        {
                $fileName=$this->DefaultPath."/Install.sql";
                //if(file_exists($fileName))
                //{
                //        unlink($fileName);
                //}
                //echo $text;
                $fp=fopen($fileName,"w+");
                fwrite($fp,$text);
        }
        
/*******************************************************
**方 法 名:RestoreTableStructure
**功能描述:备份$this->Database中所有数据表的结构
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的结构备份成功;
**                为false表示全部或部分数据表的结构备份失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function BackupTableStructure()
        {
                $i=0;
                $sqlText="";
               
                $this->GetTablesName();
                $count=count($this->TablesName);
                //
                //取出所有数据表的结构
                //
                while($i<$count)
                {
                        $tableName=$this->TablesName[$i];        
                        $result=$this->db->Query("show create table $tableName");
                        $this->db->NextRecord($result);
                        //
                        //取出成生表的SQL语句
                        //
                        $sqlText.="DROP TABLE IF EXISTS `".$tableName."`; ";//`
                        $sqlText.=$this->db->GetField(1)."; ";
                        $i++;
                }
                $sqlText=str_replace("r","",$sqlText);
                $sqlText=str_replace("n","",$sqlText);
                //$sqlText=str_replace("'","`",$sqlText);
                $this->SaveTableStructure($sqlText);
        }

/*******************************************************
**方 法 名:RestoreTableStructure
**功能描述:还原$this->Database中所有数据表的结构
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的结构还原成功;
**                为false表示全部或部分数据表的结构还原失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/        
        protected function RestoreTableStructure()
        {
                $fileName=$this->DefaultPath."/Install.sql";
                if(!file_exists($fileName)){echo "找不到表结构文件,请确认你以前做过备份!";exit;}
                $fp=fopen($fileName,"r");
               
                $sqlText=fread($fp,filesize($fileName));
                //$sqlText=str_replace("r","",$sqlText);
                //$sqlText=str_replace("n","",$sqlText);               
                $sqlArray=explode("; ",$sqlText);
                try
                {
                        $count=count($sqlArray);
                        //
                        //数组的最后一个为";",是一个无用的语句,
                        //
                        for($i=1;$i<$count;$i++)
                        {
                                $sql=$sqlArray[$i-1].";";
                                $result=$this->db->ExecuteSQL($sql);
                                if(!mysql_errno())
                                {
                                        if($i%2==0){echo "数据表".($i/2)."的结构恢复成功!n";}
                                }
                                else
                                {
                                        if($i%2==0)
                                        {
                                                echo "数据表".($i/2)."的结构恢复失败!n";
                                                exit();
                                        }
                                }
                        }
                }
                catch(Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        $this->db->Close();
                        return false;
                }
        }
        
/*******************************************************
**方 法 名:ImportData
**功能描述:导入$this->Database中所有数据表的数据从与其同名的.txt文件中,源路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据导入成功;
**                为false表示全部或部分数据表的数据导入失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/
        function ImportData()
        {
                $DataFilesName=$this->GetDataFileName();
                $count=count($this->TablesName);
                //$this->db->ExecuteSQL("set character set gbk");
                for ($i=0;$i<$count;$i++)
                {
                        //$DataFilesName[$i]=str_replace("\","/",$DataFilesName[$i])
                        //echo $DataFilesName[$i];
                        $sqlLoadData="load data infile '".$DataFilesName[$i]."'  into table ".$this->TablesName[$i];
                        $sqlCleanData="delete from ".$this->TablesName[$i];
                        //echo $sql."n";
                        try
                        {
                                //$this->db->ExecuteSQL("set character set utf8");
                                //$this->db->ExecuteSQL("SET NAMES 'utf8'");
                                $this->db->ExecuteSQL($sqlCleanData);
                                $this->db->ExecuteSQL($sqlLoadData);
                                return true;
                                //echo "数据导入成功!";
                        }
                        catch (Exception $e)
                        {
                                $this->db->ShowError($e->getMessage());
                                return false;
                                exit();
                        }
                }        
        }
        
/*******************************************************
**方 法 名:ExportData
**功能描述:导出$this->Database中所有数据表的数据到与其同名的.txt文件中,目标路径为$DefaultPath
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据导出成功;
**                为false表示全部或部分数据表的数据导出失败>
**作    者:林超旗
**日    期:2007-04-09
**修 改 人:
**日    期:
********************************************************/
        function ExportData()
        {
                $DataFilesName=$this->GetDataFileName();
                $count=count($this->TablesName);
                try
                {
                        for ($i=0;$i<$count;$i++)
                        {
                                $sql="select * from ".$this->TablesName[$i]."  into outfile '".$DataFilesName[$i]."'";
                                if(file_exists($DataFilesName[$i]))
                                {
                                        unlink($DataFilesName[$i]);
                                }
                                //$this->db->ExecuteSQL("SET NAMES 'utf8'");
                                $this->db->ExecuteSQL($sql);
                        }
                        return true;
                        //echo "数据导出成功!";
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }
        }
        
/*******************************************************
**方 法 名:BackupDatabase
**功能描述:备份$this->Database中所有数据表的结构和数据
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据库备份成功;
**                为false表示全部或部分数据表的数据库备份失败>
**作    者:林超旗
**日    期:2007-04-10
**修 改 人:
**日    期:
********************************************************/        
        function BackupDatabase()
        {
                try
                {
                        $this->BackupTableStructure();
                        $this->ExportData();
                        return true;
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }
        }
        
/*******************************************************
**方 法 名:RestoreDatabase
**功能描述:还原$this->Database中所有数据表的结构和数据
**输入参数:无         
**输出参数:无
**返 回 值:- bool<返回为true表示所有数据表的数据库还原成功;
**                为false表示全部或部分数据表的数据库还原失败>
**作    者:林超旗
**日    期:2007-04-10
**修 改 人:
**日    期:
********************************************************/        
        function RestoreDatabase()
        {
                try
                {
                        $this->RestoreTableStructure();
                        $this->ImportData();
                        return true;
                }
                catch (Exception $e)
                {
                        $this->db->ShowError($e->getMessage());
                        return false;
                        exit();
                }               
        }
}
?>[/php]

php 生成条形码
<?php
function UPCAbarcode($code) {
  $lw = 2; $hi = 100;
  $Lencode = array('0001101','0011001','0010011','0111101','0100011',
                   '0110001','0101111','0111011','0110111','0001011');
  $Rencode = array('1110010','1100110','1101100','1000010','1011100',
                   '1001110','1010000','1000100','1001000','1110100');
  $ends = '101'; $center = '01010';
  /* UPC-A Must be 11 digits, we compute the checksum. */
  if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
  /* Compute the EAN-13 Checksum digit */
  $ncode = '0'.$code;
  $even = 0; $odd = 0;
  for ($x=0;$x<12;$x++) {
    if ($x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  }
  $code.=(10 - (($odd * 3 + $even) % 10)) % 10;
  /* Create the bar encoding using a binary string */
  $bars=$ends;
  $bars.=$Lencode[$code[0]];
  for($x=1;$x<6;$x++) {
    $bars.=$Lencode[$code[$x]];
  }
  $bars.=$center;
  for($x=6;$x<12;$x++) {
    $bars.=$Rencode[$code[$x]];
  }
  $bars.=$ends;
  /* Generate the Barcode Image */
  $img = ImageCreate($lw*95+30,$hi+30);
  $fg = ImageColorAllocate($img, 0, 0, 0);
  $bg = ImageColorAllocate($img, 255, 255, 255);
  ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
  $shift=10;
  for ($x=0;$x<strlen($bars);$x++) {
    if (($x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
    if ($bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
    ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  }
  /* Add the Human Readable Label */
  ImageString($img,4,5,$hi-5,$code[0],$fg);
  for ($x=0;$x<5;$x++) {
    ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
    ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  }
  ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
  /* Output the Header and Content. */
  header("Content-Type: image/png");
  ImagePNG($img);
}
UPCAbarcode('47101496236');
?>

已测(表结构:id 表ID(唯一)title 各类标题flid 类别的ID (大类为1 中类为2 小类为3)pid 上类的ID(大类就跟大类,提交中类的时候这地方写大类的ID,提交小类的时候写中类的ID) )

<?php   $link=mysql_connect("localhost","root","root") or die("数据库服务器连接错误".mysql_error());   mysql_select_db("sanji",$link) or die("数据库访问错误".mysql_error());   mysql_query("set character set gb2312");     mysql_query("set names gb2312");?><html><head><title>下拉框连动</title></head><body><script language="JavaScript"><!--var subcat = new Array();<?$i=0;$sql="select * from sanji where flid=2";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>var subcat2 = new Array();<?$i=0;$sql="select * from sanji where flid=3";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "subcat2[".$i++."] = new Array('".$arr["pid"]."','".$arr["title"]."','".$arr["id"]."');n";}?>function changeselect1(locationid){document.form1.s2.length = 0;document.form1.s2.options[0] = new Option('==请选择==','');for (i=0; i<subcat.length; i++){if (subcat[i][0] == locationid){document.form1.s2.options[document.form1.s2.length] = new Option(subcat[i][1], subcat[i][2]);}}}function changeselect2(locationid){document.form1.s3.length = 0;document.form1.s3.options[0] = new Option('==请选择==','');for (i=0; i<subcat2.length; i++){if (subcat2[i][0] == locationid){document.form1.s3.options[document.form1.s3.length] = new Option(subcat2[i][1], subcat2[i][2]);}}}//--></script>三级联动:<BR><form name="form1"><select name="s1" onChange="changeselect1(this.value)"><option>==请选择==</option><?$sql="select * from sanji where flid=1";$query=mysql_query($sql,$link);while($arr=mysql_fetch_array($query)){echo "<option value=".$arr["id"].">".$arr["title"]."</option>n";}?></select><select name="s2" onChange="changeselect2(this.value)"><option>==请选择==</option></select><select name="s3" onChange="alert('选选择'+this.value)"><option>==请选择==</option></select></form><BR></body></html>

数据库叫"sanji"-- phpMyAdmin SQL Dump-- version 2.11.4-- http://www.phpmyadmin.net---- 主机: localhost-- 生成日期: 2009 年 11 月 03 日 15:12-- 服务器版本: 5.0.51-- PHP 版本: 5.2.5SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";---- 数据库: `sanji`---- ------------------------------------------------------------ 表的结构 `sanji`--CREATE TABLE IF NOT EXISTS `sanji` (  `id` int(10) NOT NULL auto_increment,  `title` varchar(30) collate utf8_unicode_ci NOT NULL,  `flid` int(10) NOT NULL,  `pid` int(10) NOT NULL,  PRIMARY KEY  (`id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;---- 导出表中的数据 `sanji`--INSERT INTO `sanji` (`id`, `title`, `flid`, `pid`) VALUES(1, '我是1', 1, 1),(2, '我是2,归1管', 2, 1),(3, '我是3,归2管', 3, 2),(4, '我是4,也归2管', 3, 2);

if( isset($_FILES['upImg']) )
{
 if( $userGroup[$loginArr['group']]['upload'] == 0 )
 {
  echo '{"error":"您所在的用户组无权上传图片!"}';
 }
 else
 {
  $savePath = "attachment/img/".date('Y/m/d/H');

  mkDirs($savePath);

  $fileType = strtolower(strrchr($_FILES['upImg']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upImg']['size'] > 204800 )
  {
   echo '{"error":"图片不能超过200K!"}';
  }
  else
  {
   $saveImg = $savePath."/".$loginArr['uid']."_".time().rand().$fileType;

   if( @move_uploaded_file($_FILES['upImg']['tmp_name'], $saveImg) )
   {
    echo '{"error":"","msg":"http://'.$site_domain.$site_catalog.$saveImg.'"}';
   }
   else
   {
    echo '{"error":"图片上传失败!"}';
   }
  }
 }
}

if( $loginArr['state'] == 0 )
{
 echo '{"error":"您还没有登录!"}';
}
else
{
 $avatarPath = "attachment/avatar/".($loginArr['uid']%32)."/".($loginArr['uid']%257)."/".$loginArr['uid'];

 if( isset($_FILES['upAvatar']) )
 {
  mkDirs($avatarPath);

  $fileType = strtolower(strrchr($_FILES['upAvatar']['name'],"."));

  if ( !in_array($fileType, array(".jpg",".jpeg",".gif",".png")) )
  {
   echo '{"error":"目前仅支持格式为jpg、jpeg、gif、png的图片!"}';
  }
  elseif( $_FILES['upAvatar']['size'] > 2097152 )
  {
   echo '{"error":"图片不能超过2MB!"}';
  }
  else
  {
   $imgInfo = @getimagesize($_FILES['upAvatar']['tmp_name']);

   if( !$imgInfo || !in_array($imgInfo[2], array(1,2,3)) )
   {
    echo '{"error":"系统无法识别您上传的文件!"}';
   }
   else
   {
    $TmpAvatar = $avatarPath."/temp".$fileType;
    
    if( @move_uploaded_file($_FILES['upAvatar']['tmp_name'], $TmpAvatar) )
    {
     $maxWidth = 520;

     $maxHeight = 520;

     if( $maxWidth > $imgInfo[0] || $maxHeight > $imgInfo[1] )
     {
      $maxWidth = $imgInfo[0];

      $maxHeight = $imgInfo[1];
     }
     else
     {
      if ( $imgInfo[0] < $imgInfo[1] )
       $maxWidth = ($maxHeight / $imgInfo[1]) * $imgInfo[0];
      else
       $maxHeight = ($maxWidth / $imgInfo[0]) * $imgInfo[1];
     }

     if( $maxWidth < 40 )
     {
      $maxWidth = 40;
     }

     if( $maxHeight < 40 )
     {
      $maxHeight = 40;
     }

     $image_p = imagecreatetruecolor($maxWidth, $maxHeight);

     switch($imgInfo[2])
     {
      case 1:
       $image = imagecreatefromgif($TmpAvatar);
       break;
      case 2:
       $image = imagecreatefromjpeg($TmpAvatar);
       break;
      case 3:
       $image = imagecreatefrompng($TmpAvatar);
       break;
     }

     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $imgInfo[0], $imgInfo[1]);

     imagejpeg($image_p, $avatarPath."/temp.jpg",100);

     imagedestroy($image_p);

     imagedestroy($image);

     if( $fileType != ".jpg" && file_exists($TmpAvatar) )
     {
      unlink($TmpAvatar);
     }

     echo '{"error":"","url":"'.$avatarPath.'/temp.jpg?'.rand().'","width":"'.$maxWidth.'","height":"'.$maxHeight.'"}';
    }
    else
    {
     echo '{"error":"图片上传失败!"}';
    }
   }
  }
 }

 if( isset($_POST['x'],$_POST['y'],$_POST['w'],$_POST['h']) )
 {
  if( is_numeric($_POST['x']) && is_numeric($_POST['y']) && $_POST['w'] > 0 && $_POST['h'] > 0 )
  {
   $image_p = imagecreatetruecolor(40, 40);

   $image = imagecreatefromjpeg($avatarPath."/temp.jpg");

   imagecopyresampled($image_p, $image, 0, 0, $_POST['x'], $_POST['y'], 40, 40, $_POST['w'], $_POST['h']);

   imagejpeg($image_p, $avatarPath."/40_40.jpg",100);

   imagedestroy($image_p);

   imagedestroy($image);

   unlink($avatarPath."/temp.jpg");

   echo "1";
  }
 }

 if( isset($_POST['avatar']) && $_POST['avatar'] == "delete" )
 {
  if( file_exists($avatarPath."/temp.jpg") )
  {
   unlink($avatarPath."/temp.jpg");
  }
 }
}

ob_end_flush();

error_reporting(0);
session_start();
header("Content-Type:text/html;charset=utf-8");
require("config.php");
$_SESSION["cookie_jar1"]=tempnam("temp","C2");
$url=DZ."ajax.php?inajax=1&action=checkseccode&seccodeverify=".$_GET["code"];
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_COOKIEFILE,$_SESSION["cookie_jar"]);
curl_setopt($ch,CURLOPT_COOKIEJAR,$_SESSION["cookie_jar1"]);
$html=curl_exec($ch);
preg_match("/(?<=encoding=").*?(?=")/",$html,$charset);
if($charset[0]!=="utf-8")
{
 $html=iconv($charset[0],"utf-8",$html);
}
curl_close($ch);
preg_match("/(?<=CDATA[).*?(?=])/",$html,$outs);
echo $outs[0];
?>

[!--infotagslink--]

相关文章