Sian 发表于 2016-1-9 23:13:58

制作简单图片管理系统

本帖最后由 Sian 于 2016-1-9 23:22 编辑

一、总体设计
1.1、主体分为2个页面,一个新增(包括修改),一个是列表(包括删除与查询),增删改查功能都齐全了;
1.2、设计数据库,用来存储所有图书数据,设计几个基本字段能说明问题即可;
1.3、封装几个类,主要包括 图片上传、数据分页、图片处理;

二、程序结构
2.1、公共配置文件,如数据库配置、全局配置
2.2、类:图片上传类、数据分页类、图片处理类
2.3、图片存储目录
2.4、主体功能:框架头部、框架尾部、增、改、列表(删/查)




三、程序设计(注释都写在代码中)
1、config.inc.php<?php
      // 设置字符集
      header("Content-type:text/html;charset=utf-8");
      // 设置错误提示
      error_reporting(E_ALL & ~E_NOTICE);
      // 设置时区
      date_default_timezone_set("PRC");
      // 错误输出
      set_error_handler(function($type, $message, $file, $line){
      echo "错误类型:{$type}<br/>错误信息:{$message}<br/>文件名称:{$file}<br/>行号:{$line}<br/>";
    });
    // 每页显示条数
      $num = 15;
      // 水印字符串
      $water_string = "www.yusian.com";2、db.inc.php<?php
      // 连接数据库
      mysql_connect("localhost", "root", "*****") or die("连接数据库失败!");
      // 选择数据库
      mysql_select_db("bookstore") or die("数据库选择失败!");3、add.php<?php
      include 'header.php';
      include '../classes/upload.class.php';
      include '../classes/image.class.php';
      if (isset($_POST["dosubmit"])){
                // 文件上传类
                $upload = new Upload("../uploads");
                $file = $_FILES["pic"];
                // 如果图片上传成功
                if ($file_name = $upload->save_file($file)){
                        // 保存缩略图
                        $thumb = new Image("../uploads");
                        $thumb->thumb($file_name, 100, 100, "thumb_");
                        // 写入数据库
                        $sql = "insert into books(bookname, publisher, author, price, pic, detail, ptime)
                        values('{$_POST['bookname']}', '{$_POST['publisher']}', '{$_POST['author']}', '{$_POST['price']}',
                        '{$file_name}', '{$_POST['detail']}', '".time()."')";
                        // sql执行及反馈
                        $result = mysql_query($sql);
                        $b = $result && (mysql_affected_rows() > 0);
                        echo $b ? "<br/>添加数据成功<br/>" : "<br/>添加失败!";
                }
      }
/*自动生成多条测试数据
      $temp = 100;
      while($temp > 0){
                $bookname = "BOOK".rand(10, 99);
                $pubisher = "机械工业出版社";
                $author = "Author".rand(10, 99);
                $price = rand(40, 120);
                $sql = "insert into books(bookname, publisher, author, price, pic, detail, ptime)
                        values('{$bookname}', '{$pubisher}', '{$author}', '{$price}',
                        '', '', '".time()."')";
                mysql_query($sql);      
                $temp -- ;
      }
*/
      
?>
<h3>添加图书</h3>
<form action="" method="POST" enctype="multipart/form-data">
      图书名:<input type="text" name="bookname" value="" /><br/>
      出版社:<inputtype="text" name="publisher" value="" /><br/>
      作者:<input type="text" name="author" value="" /><br/>
      价格:<input type="text" name="price" value="" /><br/>
      <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
      图片:<input type="file" name="pic" value="" /><br/>
      描述:<textarea cols="40" rows="5" name="detail"></textarea><br/>
      <inputtype="submit" name="dosubmit" value="提交" />
</form>

<?php include 'footer.php';?>4、mod.php<?php
      include 'header.php';
      include '../classes/upload.class.php';
      include '../classes/image.class.php';
      // 1、修改数据库中数据
      if (isset($_POST["dosubmit"])){
                $file = $_FILES["pic"];
                $file_name = $_POST['filename'];
                // 1.1、如果有图片,由上传图片
                if ($file["error"] != 4){
                        $upload = new Upload("../uploads");
                        // 获取旧图片的图片名
                        $old_name = $file_name;
                        // 图片上传成功
                        if ($file_name = $upload->save_file($file)){
                              // 创建一个图片处理对象
                              $image = new Image("../uploads");
                              // 保存缩略图
                              $image->thumb($file_name, 100, 100, "thumb_");
                              // 原图上加水印
                              $image->water_mark($file_name, $water_string, 9, "");
                              // 删除原来的旧图片
                              $image->delete_image($old_name);
                        }
                }
                // 1.2、数据写入数据库覆盖原有的值
                $sql = "update books set bookname = '{$_POST['bookname']}',
                publisher = '{$_POST['publisher']}', author = '{$_POST['author']}',
                price = '{$_POST['price']}', pic = '{$file_name}',
                detail = '{$_POST['detail']}' where id={$_POST['id']}";
               
                $result = mysql_query($sql);
                if($result && (mysql_affected_rows() > 0)){
                        echo "<br/>修改成功!<br/>";
                }else{
                        echo "<br/>".mysql_error()."修改失败!";
                }
      }
      
      // 2、查询单条记录数据
      if(isset($_GET['id'])) $id = $_GET['id'];
      if(isset($_POST['id'])) $id = $_POST['id'];
      $sql = "select id, bookname, publisher, author, price, pic, detail from books where id = {$id}";
      $result = mysql_query($sql);
      if(mysql_num_rows($result) > 0){
                // 记录提取到各个变量中
                list($id, $bookname, $publish, $author, $price, $pic, $detail) = mysql_fetch_row($result);
      }else{
                echo "没有查询到该记录!";
      }
?>
<h3>修改图书</h3>
<form action="mod.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" name = "id" value = "<?php echo $id ?>" />
      图书名:<input type="text" name="bookname" value="<?php echo $bookname ?>" /><br/>
      出版社:<inputtype="text" name="publisher" value="<?php echo $publish?>" /><br/>
      作者:<input type="text" name="author" value="<?php echo $author?>" /><br/>
      价格:<input type="text" name="price" value="<?php echo $price?>" /><br/>
      图片:<?php if($pic) echo "<img src=\"../uploads/thumb_$pic\" />";?>
      <input type="hidden" name="filename" value="<?php echo $pic ?>" />
      <input type="file" name="pic" value="<?php echo $pic?>" /><br/>
      描述:<textarea cols="40" rows="5" name="detail"><?php echo $detail ?></textarea><br/>
      <inputtype="submit" name="dosubmit" value="提交" />
</form>5、list.php<?php // 图书列表
      include 'header.php';
      include '../classes/image.class.php';
      include '../classes/page.class.php';
      
      /**********************删除功能***********************/      
      // 如果有删除标记则执行删除事件
      if (isset($_GET["action"]) && ($_GET["action"] == "del")){
                // 需要删除的id数组
                $id_array = array();
                if(isset($_POST["id"])){
                        // 多条记录删除通过post表单提交
                        $id_array = $_POST["id"];
                }else{
                        // 单条记录删除通过超链接提交
                        $id_array[] = $_GET["id"];
                }
                // 图片查询语句,通过删除的id号查询图片名称,以便将图片一起删除
                $picsql = "select pic from books where id in (".implode(",", $id_array).")";
                // 数据库记录删除
                $delsql = "delete from books where id in (".implode(",", $id_array).")";
                // 先查询即将被删除的图片名,再删除数据库记录
                $picres = mysql_query($picsql);
                $delres = mysql_query($delsql);
                if($delres && mysql_affected_rows() > 0){
                        // 使用图片类删除图片
                        $image = new Image("../uploads");
                        while(list($file_name) = mysql_fetch_row($picres)){
                              $image->delete_image($file_name);
                        }
                        echo "<br/>数据删除成功!<br/>";
                }else{
                        echo "<br/>数据删除失败!<br/>";
                }
      }
      /**********************搜索功能***********************/      
      // 用来拼接sql语句搜索条件的数组,拼接到sql语句中去
      $search_array = array();
      // 用来保存搜索参数的数组,方便传给后面的搜索页,传给分页对象
      $para_array = array();
      // 搜索模式的开启
      if (isset($_GET["model"]) && $_GET["model"]=="search"){
                $para_array["action"] = "search";
                $para_array["model"] = "search";
                // 兼顾搜索来源,如果是表单提交则为post请求,如果是分页到下一页则get提交
                $temp = empty($_POST) ? $_GET : $_POST;
                // 将两种请求过来的参数都保存记录到两个数组
                $bookname = isset($temp["bookname"]) ? $temp["bookname"]:NULL;
                $author = isset($temp["author"]) ? $temp["author"]: NULL;
                $price1 = isset($temp["price1"]) ? $temp["price1"]: NULL;
                $price2 = isset($temp["price2"]) ? $temp["price2"]: NULL;
                if ($bookname){
                        $search_array[] = "bookname like '%{$bookname}%'";
                        $para_array["bookname"] = $bookname;
                }
                if ($author){
                        $search_array[] = "author like '%{$author}%'";
                        $para_array["author"] = $author;
                }
                if ($price1){
                        $search_array[] = "price >= '{$price1}'";
                        $para_array["price1"] = $price1;
                }
                if ($price2){
                        $search_array[] = "price <= '{$price2}'";
                        $para_array["price2"]= $price2;
                }
      }
      // 拼接sql语句中where条件,并获取数据总数total
      $where = (count($search_array)) ? "where ".implode(" and ", $search_array) : NULL;
      $sql = "select count(*) as total from books {$where}";
      $result = mysql_query($sql);
      $data = mysql_fetch_assoc($result);
      $total = $data["total"];
      // 使用接收到的参数,拼接url并传给分页对象
      $para =http_build_query($para_array);
      $page = new Page($total, $num);      // 总条数,每页条数
      // 分布参数传递
      $page->set_current_url("list.php?{$para}");
      
      // 拼接查询语句,查询所有数据
      $sql = "select id, bookname, publisher, author, price, ptime from books {$where} order by id {$page->limit()}";
      $result = mysql_query($sql);
      
      // 搜索栏,搜索状态时显示,列表状态时隐藏
      if (isset($_GET["model"]) && $_GET["model"]=="search"){
                echo "<br/><form action=\"list.php?model=search&action=search\" method=\"POST\" >";
                $bookname = isset($bookname) ? $bookname : NULL;
                echo "按书名:<input type=\"text\" name = \"bookname\" value = '{$bookname}' size=8/> ";
                $author = isset($author) ? $author : NULL;
                echo "按作者:<input type=\"text\" name = \"author\" value = '{$author}' size=8/> ";
                $price1 = isset($price1) ? $price1 : NULL;
                echo "按价格:<input type=\"text\" name = \"price1\" value = '{$price1}' size=8/>";
                $price2 = isset($price2) ? $price2 : NULL;
                echo " - <input type=\"text\" name = \"price2\" value = '{$price2}' size=8/> ";
                echo "<input type=\"submit\" name = \"dosubmit\" value=\"搜索\"/>";
                echo "</form>";
      }
      
      // 主体数据列表
      echo "<form action=\"list.php?action=del&page={$page->cpage}\" method=\"POST\">";
      echo '<table border = "1" width = "80%" align = "center">';
      echo "<caption><h3>图书列表</h3></caption>";
      echo "<tr>";
      echo "<th> </th><th>编号</th><th>名称</th><th>出版社</th><th>作者</th><th>价格</th><th>添加时间</th><th>操作</th>";
      echo "</tr>";
      while(list($id, $bookname, $publisher, $author, $price, $ptime) = mysql_fetch_row($result)){
                echo "<tr align = 'center'>";
                echo '<td><input type="checkbox" name="id[]" value="'.$id.'"/></td>';
                echo "<td>{$id}</td>";
                echo "<td>《{$bookname}》</td>";
                echo "<td>{$publisher}</td>";
                echo "<td>{$author}</td>";
                echo "<td>¥".number_format($price, 2, ".", "'")."</td>";
                echo "<td>".date("Y-m-d H:i:s", $ptime)."</td>";
                echo "<td><a href='mod.php?action=mod&id=".$id."'>修改</a>/<a onclick='".delete_show($bookname)."' href = 'list.php?action=del&page={$page->cpage}&id=".$id."'>删除</a></td>";
                echo "</tr>";
      }
      // 末尾行,多条记录删除键,分页组件
      echo "<tr><td align=\"center\">";
      echo "<input type=\"submit\" name=\"dosubmit\" value=\"删除\" onclick = \"return confirm('你确定要删除这些图书吗?')\"/>";
      echo "</td>";
      echo "<td colspan = \"7\" align=\"right\">{$page->fpage()}</td>";
      echo "</tr></table></form>";
      
      // 删除提醒
      function delete_show($bookname){
                return "return confirm(\"你确定要删除《{$bookname}》这个图书吗?\")";
      }
      
      include 'footer.php';
?>6、header.php<?php
      include '../config.inc.php';
      include '../db.inc.php';
?>
<html>
      <head>
                <title>图书管理模块</title>
      </head>
      <body>
                <h1>图书管理</h1>
                <a href="add.php">添加图书</a> <a href="list.php">图书列表</a> <a href="list.php?model=search">搜索图书</a><br/>
7、footer.php      </body>
</html>
<?php mysql_close();?>四、源代码下载**** Hidden Message *****

Sian 发表于 2016-1-9 23:24:13

三个主体功能类:
1、image.class.php<?php
        class Image{
                private $path;
                // 构造方法,给定图片所在的目录
                public function __construct($path){
                        $this->path = $path;
                }
               
                // 1、创建缩略图
                public function thumb($filename, $w, $h, $prefix){
                        $file = $this->path."/".$filename;
                        list($width, $height, $type) = getimagesize($file);
                        // 修正比例
                        $p = 1;
                        if ($width > $height){
                                $p = $w / $width;
                                $h = $p * $height;
                        }else{
                                $p = $h / $height;
                                $w = $p * $width;
                        }
                  // 创建图片资源和新图的图片资源
                  $image = $this->get_image_source($file);
                  $image_new = imagecreatetruecolor($w, $h);
                  // 将原图的指定区域绘制到新图的指定区域即可
                  imagecopyresampled($image_new, $image, 0, 0, 0, 0, $w, $h, $width, $height);
                  // 输出图片并释放资源
                  $save_image_method = "image".$this->file_type($file);
                  $save_image_method($image_new, $this->path."/".$prefix.$filename);
                  imagedestroy($image);
                }
               
                // 2、增加图片水印
                public function water_mark($filename, $string, $position, $save_name){
                        $file = $this->path."/".$filename;
                        list($width, $height, $type) = getimagesize($file);
                        $image = $this->get_image_source($file);
                        $color = imagecolorallocate($image, 128, 128, 128);
                        $font = 5;
                        $w = imagefontwidth($font) * strlen($string);
                        $h = imagefontheight($font);
                        $x = 10;
                        $y = 10;
                        switch($position){
                                case 1:{$x = 10; $y = 10;}break;
                                case 4:{$x = 10; $y = ($height - $h)*0.5;}break;
                                case 7:{$x = 10; $y = ($height - $h) - 10;}break;
                               
                                case 2:{$x = ($width - $w)*0.5; $y = 10;}break;
                                case 5:{$x = ($width - $w)*0.5; $y = ($height - $h)*0.5;}break;
                                case 8:{$x = ($width - $w)*0.5; $y = ($height - $h) - 10;}break;
                               
                                case3:{$x = ($width - $w) - 10; $y = 10;}break;
                                case6:{$x = ($width - $w) - 10; $y = ($height - $h)*0.5;}break;
                                default:{$x = ($width - $w) - 10; $y = ($height - $h) - 10;}break;
                        }
                        imagestring($image, $font, $x, $y, $string, $color);
                  // 输出图片并释放资源
                  $save_image_method = "image".$this->file_type($file);
                  $new_filename = strlen($save_name) ? $save_name : $filename;
                  $save_image_method($image, $this->path."/".$new_filename);
                  imagedestroy($image);
                }
               
                // 3、使用unlink函数删除图片
                public function delete_image($filename){
                        $file_path = $this->path."/".$filename;
                        $thumb_path = $this->path."/thumb_".$filename;
                        if(file_exists($file_path) && $filename)unlink($file_path);
                        if(file_exists($thumb_path) && $filename)unlink($thumb_path);
                }
               
                /****************私有方法******************/
                // 获取图片文件类型
                private function file_type($file){
                        list($width, $height, $type) = getimagesize($file);
                  $type_array = array(1=>"gif", 2=>"jpeg", 3=>"png");
                  return $type_array[$type];
                }
                // 创建图片文件资源
                private function get_image_source($file){
                  $createimage = "imagecreatefrom".$this->file_type($file);
                  return $createimage($file);
                }
        }2、page.class.php<?php
        class Page{
                // 总数、每页条数、总页数、当前页码、基础url、起始条、结束条
                private $total, $number, $pages, $url, $start, $end;
                public $cpage;
                // 构造方法
                public function __construct($total = 200, $number = 10){
                        $this->total = $total;
                        $this->number = $number;
                        $this->pages = $this->get_pages();
                        $this->cpage = isset($_GET["page"]) ? $_GET["page"] : 1;
                        $this->start = ($this->cpage - 1) * $this->number + 1;
                        $end = $this->start + $number - 1;
                        $this->end = ($end > $total) ? $total : $end;
                }
                // 1、设置当前url,方便参数传递
                public function set_current_url($url){
                        if (strlen($url) == 0) $url = "./?";
                        $this->url = $url."&";
                }
               
                // 2、获取分页组件主体
                public function fpage(){
                        $array = array();
                        $number = $this->end - $this->start + 1;
                        // 将各种下标放到一个数组里再拼接,可根据需要加减组合
                        if($this->total) $array[] = "第{$this->start}-{$this->end}条";
                        if($this->pages > 1) $array[] = $this->cpage."/".$this->pages;
                        $array[] = $this->first();
                        if($this->pages > 1) $array[] = $this->flist();
                        $array[] = $this->last();
                        $array[] = "共{$this->total}条记录";
                        $array[] = "本页显示{$number}条记录";
                        $string = "";
                        foreach($array as $title){
                                $string .= $title."&nbsp&nbsp";
                        }
                        return $string;
                }
               
                // 3、数据库查询分页指令
                public function limit(){
                        return "LIMIT {$this->start}, {$this->number}";
                }
               
                /************************私有方法****************************/
                // 计算总页数
                private function get_pages(){
                        // ceil相当于(($this->total - 1)/$this->number)+1;
                        return ceil($this->total/$this->number);
                }
                // 首页 上一页
                private function first(){
                        $prev_num = $this->cpage - 1;
                        // 首页链接
                        $home_str = "<a href={$this->url}>首页</a>";
                        // 上一页链接,通过url?page=n来实现
                        $prev_str = "<a href={$this->url}page="."{$prev_num}>上一页</a>";
                        // 如果当前页是第1页,则不显示
                        return ($this->cpage > 1) ? $home_str."&nbsp".$prev_str : NULL;
                }
                // 中间页码表
                private function flist(){
                        $list = "";
                        // 默认情况下显示9个页码链接,如果总页数少于9个,则按最大数显示
                        $count = $this->pages > 9 ? 9 : $this->pages;
                        // 如果是9个,则前面4个后面4个,中间一个,因此循环从当前页往前数4个
                        $num = ceil($this->cpage - $count / 2);
                        // 如果前面不足4个,则直接从第1页开始
                        if ($this->cpage < $count / 2){
                                $num = 1;
                        }
                        // 如果后面不足4个,则最大只到最后一页
                        if ($this->cpage >= ($this->pages - $count / 2)){
                                $num = $this->pages - $count + 1;
                        }
                        // 开始循环拼接页码链接
                        for($i = 0; $i < $count; $i++){
                                $str = "<a href = {$this->url}page={$num}>{$num}</a>";
                                // 如果是当前页,则只显示数字,不加超链接
                                if($num == $this->cpage) $str = $num;
                                $list = $list.$str;
                                // 排队最后一个,中间都加两个空格隔开
                                if ($i < $count - 1) $list .= "&nbsp&nbsp&nbsp";
                                $num++;
                        }
                        return $list;
                }
                // 下一页 末页
                private function last(){
                        $next_num = $this->cpage + 1;
                        // 下一页链接,即为当前页加1
                        $next_str = "<a href={$this->url}page={$next_num}>下一页</a>";
                        // 末尾页取总页码数加链接
                        $end_str = "<a href={$this->url}page={$this->pages}>末页</a>";
                        // 如果当前为最后一页,则不显示
                        return ($this->cpage < $this->pages) ? $next_str."&nbsp".$end_str : NULL;
                }
        }3、upload.class.php<?php
        class Upload{
               
                private $path;
                // 构造方法
                function __construct($path){
                        $this->path = $path;
                }
                // 1、保存文件
                public function save_file($file){
                        if ($this->get_file($file) && $this->file_type($file) && $this->file_size($file)){
                                return $this->move($file);
                        }else{
                                return false;
                        }
                }
                /****************私有方法********************/
                // 获取文件
                private function get_file($file){
                        $error = $file["error"];
                        if($error > 0){
                                switch($error){
                                        case1: echo "上传时超过了upload_max_filesie<br/>";return false;
                                        case2: echo "超过了表单MAX_FILE_SIZE<br/>";return false;
                                        case3: echo "文件只部分上传<br/>";return false;
                                        case4: echo "没有上传任何文件<br/>";return false;
                                        default: echo "其他<br/>";return false;
                                }
                        }else{
                                return true;
                        }
                }
                // 判断文件类型
                private function file_type($file){
                        $allow_type = array("jpg", "jpeg", "png");
                        $array = explode(".", $file["name"]);
                        $file_type = end($array);
                        if (!in_array($file_type, $allow_type)){
                                echo "上传的文件类型不合法!<br/>";
                                return false;
                        }else{
                                return true;
                        }
                }
                // 判断文件大小
                private function file_size($file){
                        $max_size = 1000000;
                        if ($file["size"] > $max_size){
                                echo "上传的文件大小超出了最大值1M<br/>";return false;
                        }else{
                                return true;
                        }
                }
                // 移动文件位置
                private function move($file){
                        $array = explode(".", $file["name"]);
                        $file_type = end($array);
                        $file_name = date("YmdHis").rand(100, 999).".{$file_type}";
                        $save_url = $this->path."/".$file_name;
                        if(move_uploaded_file($file["tmp_name"], $save_url)){
                                echo "<br/>上传成功!<br/>";
                                return $file_name;
                        }else{
                                echo "<br/>上传失败!<br/>";
                                return false;
                        }
                }
        }
       
页: [1]
查看完整版本: 制作简单图片管理系统