php 为图片加水印函数和缩略图的函数代码

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

php 为图片加水印函数和缩略图的函数代码
/**
* 为图片加水印
* @param string $desImg 目标图片 参数格式为 ./images/pic.jpg
* @param string $waterImg 水印图片 参数格式同上,水印图片为 png格式,背景透明
* @param int positon 水印位置 1:顶部居左 2:顶部居右 3:居中 4 :底部居左 5:底部居右
* @param bool $saveas 是否另存为,默认值false,表示覆盖原图
* @param int $alpha 水印图片的不透明度
* @return string $savepath 新图片的路径
* **/
function watermark($desImg,$waterImg,$positon=1,$saveas=false,$alpha=30)
{
//获取目图片的基本信息
$temp=pathinfo($desImg);
$name=$temp["basename"];//文件名
$path=$temp["dirname"];//文件所在的文件夹
$extension=$temp["extension"];//文件扩展名
if($saveas)
{
//需要另存为
$name=rtrim($name,".$extension")."_2.";//重新命名
$savepath=$path."/".$name.$extension;
}
else
{
//不需要另存为则覆盖原图
$savepath=$path."/".$name;
}
$info=getImageInfo($desImg);//获取目标图片的信息
$info2=getImageInfo($waterImg);//获取水印图片的信息

$desImg=create($desImg);//从原图创建
$waterImg=create($waterImg);//从水印图片创建
//位置1:顶部居左
if($positon==1)
{
$x=0;
$y=0;
}
//位置2:顶部居右
if($positon==2)
{
$x=$info[0]-$info2[0];
$y=0;
}
//位置3:居中
if($positon==3)
{
$x=($info[0]-$info2[0])/2;
$y=($info[1]-$info2[1])/2;
}
//位置4:底部居左
if($positon==4)
{
$x=0;
$y=$info[1]-$info2[1];
}
//位置5:底部居右
if($positon==5)
{
$x=$info[0]-$info2[0];
$y=$info[1]-$info2[1];
}
imagecopymerge($desImg,$waterImg,$x,$y,0,0,$info2[0],$info2[1],$alpha);
imagejpeg($desImg,$savepath);
imagedestroy($desImg);
imagedestroy($waterImg);
return $savepath;
}
/**
* 获取图片的信息,width,height,image/type
* @param string $src 图片路径
* @return 数组
* **/
function getImageInfo($src)
{
return getimagesize($src);
}
/**
* 创建图片,返回资源类型
* @param string $src 图片路径
* @return resource $im 返回资源类型
* **/
function create($src)
{
$info=getImageInfo($src);
switch ($info[2])
{
case 1:
$im=imagecreatefromgif($src);
break;
case 2:
$im=imagecreatefromjpeg($src);
break;
case 3:
$im=imagecreatefrompng($src);
break;
}
return $im;
}
/**
* 缩略图主函数
* @param string $src 图片路径
* @param int $w 缩略图宽度
* @param int $h 缩略图高度
* @return mixed 返回缩略图路径
* **/

function resize($src,$w,$h)
{
$temp=pathinfo($src);
$name=$temp["basename"];//文件名
$dir=$temp["dirname"];//文件所在的文件夹
$extension=$temp["extension"];//文件扩展名
$savepath="{$dir}/{$name}.thumb.jpg";//缩略图保存路径,新的文件名为*.thumb.jpg

//获取图片的基本信息
$info=getImageInfo($src);
$width=$info[0];//获取图片宽度
$height=$info[1];//获取图片高度
$per1=round($width/$height,2);//计算原图长宽比
$per2=round($w/$h,2);//计算缩略图长宽比

//计算缩放比例
if($per1>$per2||$per1==$per2)
{
//原图长宽比大于或者等于缩略图长宽比,则按照宽度优先
$per=$w/$width;
}
if($per1<$per2)
{
//原图长宽比小于缩略图长宽比,则按照高度优先
$per=$h/$height;
}
$temp_w=intval($width*$per);//计算原图缩放后的宽度
$temp_h=intval($height*$per);//计算原图缩放后的高度
$temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布
$im=create($src);
imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);
if($per1>$per2)
{
imagejpeg($temp_img,$savepath);
return addBg($savepath,$w,$h,"w");
//宽度优先,在缩放之后高度不足的情况下补上背景
}
if($per1==$per2)
{
imagejpeg($temp_img,$savepath);
return $savepath;
//等比缩放
}
if($per1<$per2)
{
imagejpeg($temp_img,$savepath);

return addBg($savepath,$w,$h,"h");
//高度优先,在缩放之后宽度不足的情况下补上背景
}
}
/**
* 添加背景
* @param string $src 图片路径
* @param int $w 背景图像宽度
* @param int $h 背景图像高度
* @param String $first 决定图像最终位置的,w 宽度优先 h 高度优先 wh:等比
* @return 返回加上背景的图片
* **/
function addBg($src,$w,$h,$fisrt="w")
{
$bg=imagecreatetruecolor($w,$h);
$white = imagecolorallocate($bg,255,255,255);
imagefill($bg,0,0,$white);//填充背景

//获取目标图片信息
$info=getImageInfo($src);
$width=$info[0];//目标图片宽度
$height=$info[1];//目标图片高度
$img=create($src);
if($fisrt=="wh")
{
//等比缩放
return $src;
}
else
{
if($fisrt=="w")
{
$x=0;
$y=($h-$height)/2;//垂直居中
}
if($fisrt=="h")
{
$x=($w-$width)/2;//水平居中
$y=0;
}
imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
imagejpeg($bg,$src);
imagedestroy($bg);
imagedestroy($img);
return $src;
}

}

允许用户以AJAX的方式上传图片
·允许用户选择图片的一定区域
·最后,提供一个裁减后图片的下载地址

我们将要用到三个文件

·index.php - 包含图片上传表单以及剪切界面
·upload.php - 提供上传功能
·crop.php - 提供剪切功能

从技术角度看,流程如下所示:

1.用户上传文件(index.php)
2.index.php将上传的图片POST到upload.php以处理上传图片程序,返回JSON数据包括图片名,长和宽。
3.根据JSON里的数据和innerHTML,我们将图片放在页面上
4.初始化javascript剪切工具
5.生成下载连接(crop.php)

让我们来看看index.php

index.php是我们的主要文件,用户通过他来上传和下载图片。

我们需要YUI提供的以下几个组件:
·yahoo-dom-event.js - 操作和解析DOM
·dragdrop - 基于图片剪切工具
·element - 基于图片剪切工具
·resize - 基于图片剪切工具
·connection - 为AJAX请求, 此例通过AJAX上传
·json - 解析JSON
·imagecropper - 我们最重要的工具

当然我们要用到 Yahoo combo handling并且加上上面提到的脚本和样式表:[code]<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/2.5.2/build/resize/assets/skins/sam/resize.css"
/>
<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/2.5.2/build/imagecropper/assets/skins/sam/imagecropper.css"
/>
<!-- js -->
<script type="text/javascript"
src="http://yui.yahooapis.com/combo?2.5.2/build/yahoo-dom-event/yahoo-dom-event.js&2.5.2/build/dragdrop/dragdrop-min.js&2.5.2/build/element/element-beta-min.js&2.5.2/build/resize/resize-beta-min.js&2.5.2/build/imagecropper/imagecropper-beta-min.js&2.
5.2/build/connection/connection-min.js&2.5.2/build/json/json-min.js"></script>
[/code]然后用户一定会通过AJAX上传图片,所以我们在页面上加一个表单。[code]<form action="upload.php"
enctype="multipart/form-data" method="post" name="uploadForm"
id="uploadForm">
        Image :
<input type="file" name="uploadImage" id="uploadImage" />
<input type="button" id="uploadButton" value="Upload"/>
</form>
[/code]点击上传按钮来激活上传程序。[code]// add listeners
YAHOO.util.Event.on('uploadButton', 'click', uploader.carry);[/code]同样,我们也需要两个容器:
·imageContainer - 将包含我们上传的图片
·downloadLink - 将包含下载连接[code]<div id="imageContainer"></div>
<div id="downloadLink"></div>
[/code]两个容器事后将通过innerHTML更新

AJAX上传
对于AJAX的上传,请参见Code Central上的教程

强烈推荐此教程,我下载了示例代码,根据自己的需要改动了一点点,最后我搞了一个非常不错的JSON对象[uploader],它只有一个方法 carry。后者只是提交表单数据到一个指定的URL。[code]uploader = {
        carry: function(){
                // set form
                YAHOO.util.Connect.setForm('uploadForm', true);
                // upload image
                YAHOO.util.Connect.asyncRequest('POST', 'upload.php', {
                        upload: function(o){
                                // parse our json data
                                var jsonData = YAHOO.lang.JSON.parse(o.responseText);

                                // put image in our image container

                            
YAHOO.util.Dom.get('imageContainer').innerHTML = '<img id="yuiImg"
src="' + jsonData.image + '" width="' + jsonData.width + '" height="' +
jsonData.height + '" alt="" />';

                                // init our photoshop
                                photoshop.init(jsonData.image);

                                // get first cropped image
                                photoshop.getCroppedImage();
                        }
                });
        }
};
[/code]当上传完成,我们得到早前提到过的JSON数据。[code]{"image" : "images/myimage.jpg", "width" : "500", "height" : 400}
[/code]此数据和我们用来放置图片的容器imageContainer将以yuiImg作为id[code]YAHOO.util.Dom.get
('imageContainer').innerHTML = '<img id="yuiImg" src="' +
jsonData.image + '" width="' + jsonData.width + '" height="' +
jsonData.height + '" alt="" />';[/code]指定图片的长和宽是非常重要的,除非图片剪切工具工作不正常。
下面我们将实例化另一个JSON对象photoshop,我们一起来看看。

我们的photoshop对象[code]photoshop = {
        image: null,
        crop: null,

        init: function(image){
                // set our image
                photoshop.image = image;

                // our image cropper from the uploaded image
                photoshop.crop = new YAHOO.widget.ImageCropper('yuiImg');
                photoshop.crop.on('moveEvent', function() {
                        // get updated coordinates
                        photoshop.getCroppedImage();
                });
        },

        getCroppedImage: function(){
                var coordinates = photoshop.getCoordinates();

              var url = 'crop.php?image=' + photoshop.image +
'&cropStartX=' + coordinates.left +'&cropStartY=' +
coordinates.top +'&cropWidth=' + coordinates.width
+'&cropHeight=' + coordinates.height;
              
YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url +
'">download cropped image</a>';               

        },

        getCoordinates: function(){
                return photoshop.crop.getCropCoords();
        }
};
[/code]这个初始化方法初始化了yuiImg[code]photoshop.crop = new
YAHOO.widget.ImageCropper('yuiImg');[/code]我们同样要声明moveEvent方法,每当这个图片被移动或是被调整大小,我们就调用getCroppedImage这个方法来更新下载连接。[code]photoshop.crop.on
('moveEvent', function() {
        // get updated coordinates
        photoshop.getCroppedImage();
});
[/code]getCroppedImage方法将生成裁减后的图片地址。在PHP里实现,我们需要
·要处理的图片
·X,Y轴的坐标
·裁减后的图片长和宽

幸运的是,YUI的剪切工具里有一个方法满足了我们的需要,它就是getCropCoords()方法。所以,无论什么时候调用getCroppedImage方法,我们取到剪切图片的坐标,然后生成一个下载连接。[code]// get coordinates
var coordinates = photoshop.getCoordinates();

// build our url
var
url = 'crop.php?image=' + photoshop.image + '&cropStartX=' +
coordinates.left +'&cropStartY=' + coordinates.top
+'&cropWidth=' + coordinates.width +'&cropHeight=' +
coordinates.height;

// put download link in our page
YAHOO.util.Dom.get('downloadLink').innerHTML = '<a href="' + url + '">download cropped image</a>';
[/code]index.php的所有内容就在这里了。

upload.php[code]
          if ($ext == "jpg") {
                      // generate unique file name
                  $newName = 'images/'.time().'.'.$ext;

                  // upload files
                if ((move_uploaded_file($_FILES['uploadImage']['tmp_name'], $newName))) {

                        // get height and width for image uploaded
                        list($width, $height) = getimagesize($newName);

                        // return json data
                           echo '{"image" : "'.$newName.'", "height" : "'.$height.'", "width" : "'.$width.'" }';
                }
                else {
                           echo '{"error" : "An error occurred while moving the files"}';
                }
          }
          else {
                     echo '{"error" : "Invalid image format"}';
          }
}
[/code]upload.php就像它写的那样,只解析jpg格式的图片,然后生成一个唯一的文件名,置于images的文件夹内,最后生成DOM可操作的JSON数据。当然images文件夹要设置为可读写。

crop.php[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// force download nes image
header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'.$imgfile.'"');
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);
[/code]我们可以通过crop.php剪切上传的图片。首先我们得到所有的通过AJAX传递给我们的变量。[code]// get variables
$imgfile = $_GET['image'];
$cropStartX = $_GET['cropStartX'];
$cropStartY = $_GET['cropStartY'];
$cropW = $_GET['cropWidth'];
$cropH = $_GET['cropHeight'];
[/code]我们创建两个图片,原始图片和剪切了的图片,通过imagecopyresized方法来生成剪切图片。我们加入两个头部信息,一个告诉游览器这是一个图片,另一个是保存图片的对话框。

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');
?>

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

        //
        //包含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]

已测(表结构: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);

[!--infotagslink--]

相关文章

  • php正确禁用eval函数与误区介绍

    eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 金额阿拉伯数字转换为中文的自定义函数

    CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • PHP用strstr()函数阻止垃圾评论(通过判断a标记)

    strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
  • PHP函数分享之curl方式取得数据、模拟登陆、POST数据

    废话不多说直接上代码复制代码 代码如下:/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含POST、HEADER等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header:...2014-06-07
  • php中的foreach函数的2种用法

    Foreach 函数(PHP4/PHP5)foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。...2013-09-28
  • C语言中free函数的使用详解

    free函数是释放之前某一次malloc函数申请的空间,而且只是释放空间,并不改变指针的值。下面我们就来详细探讨下...2020-04-25
  • PHP函数strip_tags的一个bug浅析

    PHP 函数 strip_tags 提供了从字符串中去除 HTML 和 PHP 标记的功能,该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数...2014-05-31
  • SQL Server中row_number函数的常见用法示例详解

    这篇文章主要给大家介绍了关于SQL Server中row_number函数的常见用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • PHP加密解密函数详解

    分享一个PHP加密解密的函数,此函数实现了对部分变量值的加密的功能。 加密代码如下: /* *功能:对字符串进行加密处理 *参数一:需要加密的内容 *参数二:密钥 */ function passport_encrypt($str,$key){ //加密函数 srand(...2015-10-30
  • php的mail函数发送UTF-8编码中文邮件时标题乱码的解决办法

    最近遇到一个问题,就是在使用php的mail函数发送utf-8编码的中文邮件时标题出现乱码现象,而邮件正文却是正确的。最初以为是页面编码的问题,发现页面编码utf-8没有问题啊,找了半天原因,最后找到了问题所在。 1.使用 PEAR 的...2015-10-21
  • C#中加载dll并调用其函数的实现方法

    下面小编就为大家带来一篇C#中加载dll并调用其函数的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#虚函数用法实例分析

    这篇文章主要介绍了C#虚函数用法,实例分析了C#中虚函数的功能与基本使用技巧,需要的朋友可以参考下...2020-06-25
  • PHP编码转换函数mb_convert_encoding与iconv用法

    文章来实现一个PHP编码转换函数mb_convert_encoding与iconv用法,希望例子能帮助到各位。 将一个短信接口代码从apache迁移到nginx+php-fpm后,发现无法发出短信了,查...2016-11-25