我是靠谱客的博主 勤劳棒球,最近开发中收集的这篇文章主要介绍php教程--案例38(文章管理系统),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

这个演示项目,我把文件夹目录建立的简单,没有分层级,都是同级目录。根目录cms_1。

根目录一级目录二级目录
cms_1  
 lib 
  ueditor
 article_add.php 
 article_del.php 
 article_edit.php 
 article_show.php 
 category.php 
 category_list.php 
 fetch_categorylist.php 
 header.php 
 index.php 
 init.php 
 myEditor.php 
 MySQLPDO.php 
 page.class.php 

我下载的ueditor版本,文件名是ucbug.com-Ueditor.rar;文件结构如图,请把全部文件放置在cms_1/lib/ueditor里面。

下面我把代码贴出来;

MySQLPDO.php

<?php
//case 38 文章管理系统

/**
 * Class MySQLPDO
 *
 * create table cms_category(
id int unsigned auto_increment primary key,
name varchar(255) not null comment '分类名称',
sort int unsigned default 0 not null comment '排序'
)charset=utf8;
 *
 * create table cms_article(
id int unsigned primary key auto_increment,
title varchar(255) not null comment '文章标题',
content text not null comment '文章内容',
author varchar(255) not null comment '作者',
addtime timestamp default current_timestamp not null comment '添加时间',
cid int unsigned not null comment '文章所属分类'
)charset=utf8;
 *
 *
 *
 *
 */
//数据库操作类
class MySQLPDO
{
    //配置
    private $dbConfig = array(
        'db'=>'mysql',
        'host'=>'localhost',
        'port'=>'3306',
        'user'=>'root',
        'pass'=>'mysql123',
        'charset'=>'utf8',
        'dbname'=>'test',
    );
    //静态实例
    private static $instance;
    //数据库链接
    private $db;
    //数据数组
    private $data = array();

    /**
     * MySQLPDO constructor.
     * @param $params
     */
    //构造函数
    private function __construct($params)
    {
        $this->dbConfig = array_merge($this->dbConfig,$params);
        $this->connect();
    }

    /**
     * @param array $params
     * @return MySQLPDO
     */
    //获取实例
    public static function getInstance($params = array())
    {
        if(!self::$instance instanceof self)
        {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     *
     */
    private function __clone()
    {

    }

    /**
     *
     */
    //连接
    private function connect()
    {
        $dsn = "{$this->dbConfig['db']}:host={$this->dbConfig['host']};port={$this->dbConfig['port']};dbname={$this->dbConfig['dbname']};charset={$this->dbConfig['charset']};}";
        try
        {
            $this->db = new PDO($dsn,$this->dbConfig['user'],$this->dbConfig['pass']);

        }
        catch (PDOException $e)
        {
            die("数据库连接失败");
        }
    }

    /**
     * @param $sql
     * @param bool $batch
     * @return mixed
     */
    //执行查询
    public function query($sql,$batch=false)
    {
        $data = $batch?$this->data:array($this->data);
        $this->data = array();
        $stmt = $this->db->prepare($sql);
        foreach ($data as $v)
        {
            if($stmt->execute($v) === false)
            {
                die("数据库操作失败");
            }
        }
        return $stmt;
    }

    /**
     * @param $data
     * @return $this
     */
    //数据数组
    public function data($data)
    {
        $this->data = $data;
        return $this;
    }
    //取单行
    public function fetchRow($sql)
    {
        return $this->query($sql)->fetch(PDO::FETCH_ASSOC);
    }
    //取全部
    public function fetchAll($sql)
    {
        return $this->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    }


}




index.php

<?php
//根据分类取文章列表,暂时没有用到
//$cid = isset($_GET['cid'])?intval($_GET['cid']):0;
$where = '';
//if($cid)
//{
//    $where = "where cid=$cid";
//}

//引入数据库初始化
require_once ('./init.php');
//分页类
require_once ('./page.class.php');
//当前页码
$page = isset($_GET['page'])?intval($_GET['page']):1;
//统计总条数
$sql = "select count(*) as total from cms_article $where";
$results = $db->fetchRow($sql);
//总记录数
$total = $results['total'];
//分页
$page = new Page1($total,2,$page);
//分页条件
$limit = $page->getLimit();
//分页
$page_html = $page->showPage();
//取文章
$sql = "select * from cms_article $where order by addtime desc limit $limit";
$articles = $db->fetchAll($sql);
foreach ($articles as $key=>$value)
{
    //截取内容
    $articles[$key]['content'] = mb_substr(trim(strip_tags($value['content'])),0,150,'utf-8').'... ...';
}

?>

<html>
<head>
    <title>首页</title>
</head>
<body>
<ul style="list-style: none;">
    <?php foreach ($articles as $row):?>
    <li>
        <span style="min-width: 300px;display: inline-block;">
            <a href="./article_show.php?id=<?= $row['id'];?>"><?= $row['title'];?></a>
        </span>
        <span>
            <a href="./article_edit.php?id=<?= $row['id'];?>">编辑</a>
            &nbsp;
            <a href="./article_del.php?id=<?= $row['id'];?>" onclick="{if(confirm('确定要删除改文章吗?')){return true;}return false;}">删除</a>
        </span>
        <p><?= $row['content'];?></p>
        <p style="text-align: center;"><a href="./article_show.php?id=<?= $row['id'];?>">单击查看全文&gt;&gt;</a></p>
        <p>
            发表时间:<span><?= $row['addtime'];?></span>
            作者:<span><?= $row['author'];?></span>
        </p>
    </li>
    <?php endforeach;?>
    <div><?php echo $page_html;?></div>
    <div><a href="./article_add.php">添加文章</a></div>
</ul>
</body>
</html>


init.php

<?php
header('content-type:text/html;charset=utf-8');
require_once './MySQLPDO.php';
$dbConfig = array('user'=>'root','pass'=>'mysql123','dbname'=>'test');
$db = MySQLPDO::getInstance($dbConfig);
$error = array();


page.class.php

<?php

class Page1
{
    //总记录数
    private $total;
    //每页显示记录数
    private $page_size;
    //当前页
    private $current;
    //总的页数
    private $page_num;

    /**
     * Page1 constructor.
     * @param $total
     * @param $page_size
     * @param $current
     */
    //构造函数
    public function __construct($total,$page_size,$current)
    {
        $this->total = $total;
        $this->page_size = $page_size;
        $this->current = $current;
        //取整数
        $this->page_num = ceil($this->total / $this->page_size);

    }

    /**
     * @return string
     */
    //获取sql的limit条件
    public function getLimit()
    {
        $lim = ($this->current - 1) * $this->page_size;
        return $lim.','.$this->page_size;
    }

    /**
     * @return array
     */
    //获得URL参数
    private function getUrlParams()
    {
        $p = array();
        unset($_GET['page']);
        foreach ($_GET as $key=>$value)
        {
            $p[] = "$key=$value";
        }

        return $p;
    }

    /**
     * @return string
     */
    //获取分页链接
    public function showPage()
    {
        if($this->page_num < 1)
            return '';
        $url = $this->getUrlParams();
        $url = '?'.implode('&',$url).'page=';
        $first = '<a href="'.$url.'1">[首页]</a>';
        $prev = ($this->current == 1)?'[上一页]':'<a href="'.$url.($this->current - 1).'">[上一页]</a>';
        $next = ($this->current == $this->page_num)?'[下一页]':'<a href="'.$url.($this->current + 1).'">[下一页]</a>';
        $last = '<a href="'.$url.$this->page_num.'">[尾页]</a>';
        return "当前为{$this->current}/{$this->page_num} {$first} {$prev} {$next} {$last}";

    }


}

myEditor.php

<div>
    <!-- 默认样式-->
    <link href="./lib/ueditor/themes/default/css/ueditor.min.css" rel="stylesheet">
    <!-- jquery-->
    <script src="./lib/ueditor/third-party/jquery-1.10.2.min.js"></script>
    <!-- 配置文件-->
    <script src="./lib/ueditor/ueditor.config.js"></script>
    <!-- 主要文件-->
    <script src="./lib/ueditor/ueditor.all.min.js"></script>
    <!-- 语言-->
    <script src="lib/ueditor/lang/zh-cn/zh-cn.js"></script>
    <!-- 实例化 id很重要-->
    <script>
        var ue = UE.getEditor('myEditor');
        /*
        $(function () {
            UE.getEditor('myEditor',{
        toolbars: [[
        'fullscreen', 'source', '|', 'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
        'directionalityltr', 'directionalityrtl', 'indent', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
        'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
        'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
        'print', 'preview', 'searchreplace', 'drafts', 'help'
        ]]
            });
        });
        */
    </script>
</div>

header.php

<!--错误信息-->
<?php if(!empty($error)):?>
<div>
    <ul>
        <?php foreach ($error as $v):?>
        <li><?= $v;?></li>
        <?php endforeach;?>
    </ul>
</div>
<?php endif;?>

fetch_categorylist.php

<?php
require_once ('./init.php');
$sql = "select id,name from cms_category order by sort asc";
$category1 = $db->fetchAll($sql);
?>

文章分类:<select name="category_list" style="width: 150px;">
    <?php foreach ($category1 as $value):?>
    <option value="<?= $value['id'];?>"><?= $value['name'];?></option>
    <?php endforeach;?>
</select>

category_list.php

<html>
<head>
    <title>文章分类</title>
</head>
<body>
<?php require_once ('./header.php');?>
<!--添加文章分类表当-->
<form action="?a=category_add" method="post">
    分类名称:<input type="text" name="name">
    <input type="submit" name="g_add" value="添加">
</form>
<!--展示文章分类信息-->
<form method="post" action="?a=category_order">
    <table>
        <tr>
            <td>排序</td>
            <td>分类名称</td>
            <td>操作</td>
        </tr>
        <?php foreach ($category as $value): ?>
        <tr>
            <td><input type="text" name="<?= $value['id'];?>" value="<?= $value['sort'];?>"></td>
            <td><?= $value['name'];?></td>
            <td><a href="?id=<?= $value['id'];?>&a=category_del" onclick="{if(confirm('确定要删除该文章分类吗?')){return true;}return false;}">删除</a>|编辑</td>
        </tr>
        <?php endforeach;?>
    </table>
    <div><input type="submit" value="保存排序"></div>
</form>
</body>
</html>

category.php

<?php
require_once ('./init.php');

$a = isset($_GET['a'])?$_GET['a']:'';
if($a == 'category_add')
{
    $data['name'] = trim(htmlspecialchars($_POST['name']));
    if($data['name'] === '')
    {
        $error[] = '文章分类名称不能为空!';
    }
    else
    {
        $sql = "select id from cms_category where name=:name";
        if($db->data($data)->fetchRow($sql))
        {
            $error[] = '该文章分类名称已经存在!';
        }
        else
        {
            $sql = "insert into cms_category(name) values(:name)";
            $db->data($data)->query($sql);
        }

    }

}
elseif($a == 'category_order')
{
    $sql = "select id from cms_category";
    $result = $db->fetchAll($sql);
    $data = array();
    foreach ($result as $v)
    {
        $data[] = array(
            'id'=>$v['id'],
            'sort'=>isset($_POST[$v['id']])?intval($_POST[$v['id']]):0
        );
    }
    $sql = "update cms_category set sort = :sort where id=:id";
    $db->data($data)->query($sql,true);

}
elseif($a == 'category_del')
{
    $id = isset($_GET['id'])?intval($_GET['id']):0;
    $sql = "select id from cms_article where cid=$id limit 1";
    if($db->fetchRow($sql))
    {
        $error[] = '该文章分类下有文章,不能删除!';
    }
    else
    {
        $sql = "delete from cms_category where id=$id";
        $db->query($sql);
    }
}

$sql = "select id,name,sort from cms_category order by sort asc";
$category = $db->fetchAll($sql);

//引入文件放入位置很关键,放在上面,error数组不显示
require_once ('./category_list.php');



?>

article_add.php

<html>
<head>
    <title>添加文章</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
<form method="post">
    <?php require_once ('./fetch_categroylist.php');?>

    <a href="category.php">分类管理</a><br>
    文章标题:<input type="text" name="title" style="width: 500px;">
    作者:<input type="text" name="author" style="width: 200px;">

    <?php require_once ('./myEditor.php');?>
    <script type="text/plain" id="myEditor" style="width:960px;height: 250px;" name="content">
        <p>请在这里编写文章.....</p>
    </script>
    <input type="submit" value="提交" style="width: 180px;" name="article_ok">
    <input type="button" value="取消" style="width: 180px;" onclick="{if(confirm('确定要取消添加文章吗?')){window.location.href='index.php';return false;}}">
</form>
</body>
</html>

<?php
if(isset($_POST['article_ok']))
{
    $data['cid'] = isset($_POST['category_list'])?abs(intval($_POST['category_list'])):0;
    $data['title'] = isset($_POST['title'])?trim(htmlspecialchars($_POST['title'])):'';
    $data['author'] = isset($_POST['author'])?trim(htmlspecialchars($_POST['author'])):'';
    $data['content'] = isset($_POST['content'])?trim($_POST['content']):'';
    if(empty($data['cid']) || empty($data['title']) || empty($data['author']))
    {
        $error = '文章分类、标题、作者不能为空!';
        echo "<script>alert('$error');</script>";
        die();
    }
    else
    {
        $sql = "insert into cms_article(title,content,author,addtime,cid) values (:title,:content,:author,now(),:cid)";
        $db->data($data)->query($sql);
        header("location:index.php");
    }
}
?>

article_del.php

<?php

require_once ('./init.php');

$id = isset($_GET['id'])?intval($_GET['id']):0;
if($id)
{
    $sql = "delete from cms_article where id=$id";
    $db->query($sql);
    header('location:index.php');
}

article_edit.php

<?php
require_once ('./init.php');
$id = isset($_GET['id'])?intval($_GET['id']):0;
$sql = "select id,name from cms_category order by sort limit 10";
$category = $db->fetchAll($sql);
if($id)
{
    $sql = "select title,content,author,cid from cms_article where id=$id";
    $rst = $db->fetchRow($sql);
    if(!empty($_POST))
    {
        $data['cid'] = isset($_POST['category'])?abs(intval($_POST['category'])):0;
        $data['title'] = isset($_POST['title'])?trim(htmlspecialchars($_POST['title'])):'';
        $data['author'] = isset($_POST['author'])?trim(htmlspecialchars($_POST['author'])):'';
        $data['content'] = isset($_POST['content'])?trim($_POST['content']):'';
        if(empty($data['cid']) || empty($data['title']) || empty($data['author']))
        {
            $error = '文章分类、标题、作者不能为空!';
            echo "<script>alert('$error');</script>";
            die();
        }
        else
        {
            $sql = "update cms_article set title=:title,content=:content,author=:author,cid=:cid where id=$id";
            $db->data($data)->query($sql);
            header("location:index.php");

        }
    }
}

?>

<html>
<head>
    <title>编辑文章</title>
</head>
<body>
<form method="post">
    文章分类:<select name="category">
        <?php foreach ($category as $v):
            if($v['id'] == $rst['cid']):?>
        <option value="<?= $v['id'];?>" selected="selected"><?= $v['name'];?></option>
        <?php else: ?>
        <option value="<?= $v['id'];?>"><?= $v['name'];?></option>
        <?php endif;?>
        <?php endforeach;?>
    </select>
    <a href="category.php">分类管理</a>
    <br>
    标题:<input type="text" name="title" value="<?= $rst['title'];?>">
    作者:<input type="text" name="author" value="<?= $rst['author'];?>">

    <?php require_once ('./myEditor.php');?>
    <script type="text/plain" id="myEditor" style="width:960px;height: 250px;" name="content">
        <?= $rst['content'];?>
    </script>
    <input type="submit" value="提交" >
    <input type="button" value="取消" onclick="{if(confirm('确定要取消修改文章吗?')){window.location.href='index.php';}return false;}">
</form>
</body>
</html>

article_show.php

<?php
require_once ('./init.php');
$id = isset($_GET['id'])?intval($_GET['id']):0;
$sql = "select * from cms_category order by sort limit 10";
$category = $db->fetchAll($sql);
if($id)
{
    $sql = "select * from cms_article where id=$id";
    $rst = $db->fetchRow($sql);
    $sql = "select name from cms_category where id=".$rst['cid'];
    $cname = $db->fetchRow($sql);
    $rst['cname'] = $cname['name'];

}

?>

<html>
<head>
    <title>展示文章</title>
</head>
<body>
<div>
    <h2><?= $rst['title'];?></h2>
    <span>时间:<?= $rst['addtime'];?></span>
    <span>分类:<?= $rst['cname'];?></span>
    <span>作者:<?= $rst['author'];?></span>
</div>
<div><?php echo $rst['content'];?></div>
</body>
</html>

 

最后

以上就是勤劳棒球为你收集整理的php教程--案例38(文章管理系统)的全部内容,希望文章能够帮你解决php教程--案例38(文章管理系统)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部