PHP5实现简单的mvc用户管理功能的增删改查实例

利用PHP简单的实现了一下MVC的设计方法:

M :数据  V:网页   C:控制输出什么网页

开发环境:phpstrom2018 ,php5

测试:使用ide内置的server测试

功能:实现了用户的增删改查

效果图:

 

 

代码结构:

 

Framework  mvc框架代码实现:

BaseController.class.php

<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 14:01
 */

/**
 * Class BaseController
 * 控制器基础类
 */
class BaseController
{
    function __construct()
    {
        header("content-type=text/html;chaset=utf8");
    }

    function GotoUrl($msg, $url, $time)
    {
        echo "<font color=red>$msg</font>";
        echo "<a href='$url'>返回</a>";
        echo '页面将在' . $time . '秒之后跳转';
        header("refresh:$time;url=$url");
    }

}

BaseModel.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 14:00
 */

/**
 * Class BaseModel
 * <br>
 * 构建mysql链接
 */
class BaseModel
{
    protected $db = null;

    function __construct()
    {
        $config = array('host' => '127.0.0.1',
            'port' => 3306,
            'user' => 'root',
            'pass' => '123456',
            'charset' => 'utf8',
            'dbname' => 'phpdemo'
        );
        $this->db = MysqlDB::GetInstance($config);
    }
}

ModelFactory.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 14:00
 */

/**
 * Class ModelFactory
 * <br>
 * 单例模型工厂
 */
class ModelFactory
{
    static $all_model = array();

    static function M($model_name)
    {
        if (!isset(static::$all_model[$model_name]) || !(static::$all_model[$model_name] instanceof $model_name)) {
            static::$all_model[$model_name] = new $model_name();
        }
        return static::$all_model[$model_name];
    }
}

MysqlDB.class.php

 

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 14:00
 */

/**
 * Class MysqlDB
 * <br>
 * MySql工具单例
 */
class MysqlDB
{
    private static $instance = null;
    private $link = null;

    private function __construct($config)
    {
        $this->link = mysqli_connect("{$config['host']}", "{$config['user']}", "{$config['pass']}", "{$config['dbname']}", "{$config['port']}");

        if (!$this->link) {
            echo "Error: Unable to connect to MySQL." . PHP_EOL;
            echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
            echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
            die("连接失败");
        }

        echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
        echo "Host information: " . mysqli_get_host_info($this->link) . PHP_EOL;

        $this->setCharset($config['charset']);
        //  $this->selectDB($config['dbname']);
    }

    static function GetInstance($config)
    {
        if (!isset(self::$instance)) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    function setCharset($charset)
    {
        mysqli_query($this->link, "set names $charset");
    }

    function selectDB($dbname)
    {
        mysqli_query($this->link, "use $dbname");
    }

    function closeDB()
    {
        mysqli_close($this->link);
    }

    function exec($sql)
    {
        $result = mysqli_query($this->link, $sql);
        if ($result === false) {
            echo '错误代码:' . mysqli_errno($this->link);
            echo '错误消息:' . mysqli_error($this->link);
            die();
        }
        return $result;
    }

    function GetOneRow($sql)
    {
        $result = $this->exec($sql);
        $rec = mysqli_fetch_assoc($result);
        mysqli_free_result($result);
        return $rec;
    }

    function GetRows($sql)
    {
        $result = $this->exec($sql);
        $arr = array();
        while ($rec = mysqli_fetch_assoc($result)) {
            $arr[] = $rec;
        }
        mysqli_free_result($result);
        return $arr;
    }

    function GetOneData($sql)
    {
        $result = $this->exec($sql);
        print_r($result);
        $rec = mysqli_fetch_row($result);

        $data = $rec[0];
        mysqli_free_result($result);
        return $data;
    }


}

Application   front   前台应用代码:

控制层:

UserController.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 18:43
 */

/**
 * Class UserController
 * <br>
 * 页面跳转和业务逻辑处理
 */
class UserController extends BaseController
{

    function IndexAction()
    {
        $obj_user = ModelFactory::M('UserModel');
        $data1 = $obj_user->GetAllUser();
        $data2 = $obj_user->GetUserCount();

        // print_r($data1);
        //  print_r($data2);

        include VIEW_PATH . 'showAllUserView.html';
    }

    function AddAction()
    {
        echo "新增信息";

        if (!empty($_POST) and count($_POST) > 0) {

            $age = $_POST['age'];
            $edu = $_POST['edu'];
            $from = $_POST['from'];
            var_dump($_POST['xinqu']);
            $xinqu = implode(",", $_POST['xinqu']);

            $obj_user = ModelFactory::M('UserModel');

            $obj_user->AddUser($age, $edu, $xinqu, $from);

            $this->GotoUrl("新增成功", "?c=User&a=index", 3);
        } else {
            include VIEW_PATH . 'AddUserView.html';
        }

    }

    function DetailAction()
    {
        echo "查看详情";

        $id = $_GET['id'];

        echo $id;

        $obj_user = ModelFactory::M('UserModel');

        $data = $obj_user->GetOneUser($id);

        include VIEW_PATH . 'detailUserView.html';


    }

    function EditAction()
    {
        echo "修改信息";

        if (!empty($_POST) and count($_POST) > 0) {
            $id = $_POST['id'];
            $age = $_POST['age'];
            $edu = $_POST['edu'];
            $from = $_POST['from'];
            $xinqu = implode(",", $_POST['xinqu']);

            $obj_user = ModelFactory::M('UserModel');

            $data = $obj_user->UpdateUser($id, $age, $edu, $xinqu, $from);

            $this->GotoUrl("修改成功", "?c=User&a=index", 3);

        } else {
            $id = $_GET['id'];
            include VIEW_PATH . 'editUserView.html';
        }
    }


    function DeleteAction()
    {
        echo "删除信息";
        $id = $_GET['id'];

        echo $id;

        $obj_user = ModelFactory::M('UserModel');

        $data = $obj_user->DeleteUser($id);

        $this->GotoUrl("删除成功", "?c=user&a=index", 3);

    }

}

模型层:

UserModel.class.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/7
 * Time: 18:52
 */

//require FRAMEWORK . 'BaseModel.class.php';

/**
 * Class UserModel
 * <br>
 * 数据层操作
 */
class UserModel extends BaseModel
{

    function GetAllUser()
    {
        $sql = "select * from user_list";
        $data = $this->db->GetRows($sql);
        return $data;
    }


    function GetUserCount()
    {
        $sql = "select count(1) from user_list";
        $data = $this->db->GetOneData($sql);
        return $data;

    }


    function GetOneUser($id)
    {
        $sql = "select * from user_list where id=$id";
        $result = $this->db->GetOneRow($sql);
        return $result;

    }

    function DeleteUser($id)
    {
        $sql = "delete from user_list where id =$id";
        $result = $this->db->exec($sql);
        return $result;
    }


    function AddUser($age, $edu, $xinqu, $from)
    {
        $sql = "insert into user_list(age,edu,xinqu,`from`,reg_time) values ($age,'$edu','$xinqu','$from',now())";
        $result = $this->db->exec($sql);
        return $result;
    }

    function UpdateUser($id, $age, $edu, $xinqu, $from)
    {
        $sql = "update user_list set id =$id";

        if (!empty($age)) {
            $sql .= ",age =$age";
        }
        if (!empty($edu)) {
            $sql .= ",edu ='$edu'";
        }
        if (!empty($xinqu)) {
            $sql .= ",xinqu ='$xinqu'";
        }
        if (!empty($from)) {
            $sql .= ",`from` ='$from'";
        }
        $sql .= " where id =$id";


       // echo $sql;

        $result = $this->db->exec($sql);

        return $result;

    }


}

视图层:

新增用户:

AddUserView.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="post" action="?c=user&a=add">
    <table border="1">
        <tr>
            <td>年龄</td>
            <td><input value="" type="text" name="age"/></td>
        </tr>
        <tr>
            <td>教育</td>
            <td><select name="edu">
                <option value="本科" selected="selected">本科</option>
                <option value="高中">高中</option>
                <option value="初中">初中</option>
                <option value="小学">小学</option>
            </select></td>
        </tr>
        <tr>
            <td>兴趣</td>
            <td>
                篮球<input name ="xinqu[]" type="checkbox" value="篮球"/>
                足球<input name ="xinqu[]"  type="checkbox" value="足球"/>
                冰球<input name ="xinqu[]" type="checkbox" value="冰球"/>
            </td>
        </tr>
        <tr>
            <td>地区</td>
            <td>
                <select name="from">
                    <option value="北京" selected="selected">北京</option>
                    <option value="上海">上海</option>
                    <option value="武汉">武汉</option>
                    <option value="合肥">合肥</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input value="添加" type="submit"/></td>
            <td><input value="重置" type="reset"/></td>
        </tr>
    </table>
</form>


</body>
</html>

用户详情:

detailUserView.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>

    <?php
        foreach($data as $key=>$value)
    {
    echo $key.":".$value."<br>";
    }
    ?>

</div>
</body>
</html>

修改用户页面

editUserView.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form method="post" action="?c=user&a=edit">
    <input type="hidden" value="<?php echo $id; ?>" name="id"/>
    <table border="1">
        <tr>
            <td>年龄</td>
            <td><input value="" type="text" name="age"/></td>
        </tr>
        <tr>
            <td>教育</td>
            <td><select name="edu">
                <option value="本科" selected="selected">本科</option>
                <option value="高中">高中</option>
                <option value="初中">初中</option>
                <option value="小学">小学</option>
            </select></td>
        </tr>
        <tr>
            <td>兴趣</td>
            <td>
                篮球<input name="xinqu[]" type="checkbox" value="篮球"/>
                足球<input name="xinqu[]" type="checkbox" value="足球"/>
                冰球<input name="xinqu[]" type="checkbox" value="冰球"/>
            </td>
        </tr>
        <tr>
            <td>地区</td>
            <td>
                <select name="from">
                    <option value="北京" selected="selected">北京</option>
                    <option value="上海">上海</option>
                    <option value="武汉">武汉</option>
                    <option value="合肥">合肥</option>
                </select>
            </td>
        </tr>
        <tr>
            <td><input value="修改" type="submit"/></td>
            <td><input value="重置" type="reset"/></td>
        </tr>
    </table>
</form>
</body>
</html>

用户列表页面:

showAllUserView.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>用户列表:<a href="?a=add&c=user">新增</a></div>
<div>
    <table border="1">
        <?php foreach($data1 as $key=>$rec){ ?>
        <tr>
            <td><?php echo $rec['id']; ?></td>
            <td><?php echo $rec['age']; ?></td>
            <td><?php echo $rec['edu']; ?></td>
            <td><?php echo $rec['xinqu']; ?></td>
            <td><?php echo $rec['from']; ?></td>
            <td><?php echo $rec['reg_time']; ?></td>
            <td><a href="?a=detail&id=<?php echo $rec['id'] ?>">详细</a></td>
            <td><a href="?a=edit&id=<?php echo $rec['id'] ?>">编辑</a></td>
            <td><a href="?a=delete&id=<?php echo $rec['id'] ?>">删除</a></td>
        </tr>
        <?php }?>
    </table>
</div>
<div>用户总数:<?php echo $data2 ?></div>
</body>
</html>

 

项目入口文件(启动整个mvc项目):

index.php

<?php

$p = !empty($_GET['p']) ? $_GET['p'] : "front"; //判断进入那个应用

define("PLAT", $p);
define("DS", DIRECTORY_SEPARATOR);//目录分隔符

define("ROOT", __DIR__ . DS); //平台根目录
define("APP", ROOT . 'Application' . DS); //应用根目录
define("FRAMEWORK", ROOT . 'Framework' . DS); //框架根目录

define("PLAT_PATH", APP . PLAT . DS); //应用目录
define("CTRL_PATH", PLAT_PATH . 'Controllers' . DS);  //控制器目录
define("MODEL_PATH", PLAT_PATH . 'Models' . DS); //模型目录
define("VIEW_PATH", PLAT_PATH . 'Views' . DS); //视图目录

/**
 * @param $class
 * 自动加载模块
 */
function __autoload($class)
{
    $base_class = array('MysqlDB', 'BaseModel', 'ModelFactory', 'BaseController');

    if (in_array($class, $base_class)) {
        require FRAMEWORK . $class . '.class.php';
    } else if (substr($class, -5) == 'Model') {
        require MODEL_PATH . $class . '.class.php';
    } else if (substr($class, -10) == 'Controller') {
        require CTRL_PATH . $class . '.class.php';
    }
}

$c = !empty($_GET['c']) ? $_GET['c'] : "User";
$controller_name = $c . 'Controller';
$ctrl = new $controller_name(); //可变类

$a = !empty($_GET['a']) ? $_GET['a'] : "index";
$action = $a . "Action";
$ctrl->$action(); //可变方法

//访问首页默认进入前台用户页面

?>


<?php

echo "<br>********************************";
echo "<br>平台已成功启动";
echo "<br>********************************";

?>

 

数据库脚本:

/*
 Navicat Premium Data Transfer

 Source Server         : localhost_3306
 Source Server Type    : MySQL
 Source Server Version : 50716
 Source Host           : localhost:3306
 Source Schema         : phpdemo

 Target Server Type    : MySQL
 Target Server Version : 50716
 File Encoding         : 65001

*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for admin_user
-- ----------------------------
DROP TABLE IF EXISTS `admin_user`;
CREATE TABLE `admin_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `admin_name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `admin_pass` varchar(48) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `login_times` int(11) NULL DEFAULT NULL COMMENT '登录次数',
  `last_login_time` datetime(0) NULL DEFAULT NULL COMMENT '最后登录时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `admin_name`(`admin_name`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of admin_user
-- ----------------------------
INSERT INTO `admin_user` VALUES (1, 'fhf', 'ghdgh', 454, '2019-06-07 19:02:14');

-- ----------------------------
-- Table structure for user_list
-- ----------------------------
DROP TABLE IF EXISTS `user_list`;
CREATE TABLE `user_list`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) NOT NULL,
  `edu` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '教育程度',
  `xinqu` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '兴趣爱好',
  `from` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地区',
  `reg_time` datetime(0) NULL DEFAULT NULL COMMENT '注册时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 13 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of user_list
-- ----------------------------
INSERT INTO `user_list` VALUES (1, 24, '大学', '足球,篮球', '湖北', '2019-06-08 01:14:52');
INSERT INTO `user_list` VALUES (9, 89, '高中', '足球', '武汉', '2019-06-08 22:54:43');
INSERT INTO `user_list` VALUES (10, 22, '初中', '篮球,足球,冰球', '武汉', '2019-06-08 22:59:27');
INSERT INTO `user_list` VALUES (11, 54, '本科', '篮球', '武汉', '2019-06-08 23:56:46');
INSERT INTO `user_list` VALUES (12, 25, '高中', '足球,冰球', '武汉', '2019-06-08 23:58:48');

SET FOREIGN_KEY_CHECKS = 1;

禁用目录访问:

.htaccess

Deny from All

使用phpstrom启动配置:

 

 

 

 

 

首页访问地址:

http://localhost/index.php

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值