Medoo框架实现演员管理

原创2019-01-19 14:21:08124
摘要:本章主要学习通过Medoo框架实现增删改查和判断数据是否存在、判断指定条件的数据行数等。通过学习,对本章进行练习,结合smarty模板,实现日本演员的维护界面。代码如下:<?php require_once __DIR__.'/sqlHelp.php'; require_once __DIR__.'/config/config.php'

本章主要学习通过Medoo框架实现增删改查和判断数据是否存在、判断指定条件的数据行数等。通过学习,对本章进行练习,结合smarty模板,实现日本演员的维护界面。代码如下:

<?php

require_once __DIR__.'/sqlHelp.php';

require_once __DIR__.'/config/config.php';

$rows=select('user',['uid','name','phone','weight','height','add_time'],["uid[<]"=>50,'ORDER'=>["uid"=>"ASC"]]);

$smarty->assign('rows',$rows);

$smarty->display(__DIR__.'/temp/showTable.html');

?>

sqlHelp.php

<?php

    require __DIR__.'/vendor/catfan/medoo/src/Medoo.php';

    use Medoo\Medoo as Db;

    //数据库配置参数
    $config = [
        //必填
        'database_type' => 'mysql',    //数据库类型
        'database_name' => 'test',   //默认数据库名称
        'server' => 'localhost',  //默认数据库主机名
        'username' => 'root',    //默认用户名称
        'password' => 'root',   //用户密码

        // 可选
        'charset' => 'utf8',    //默认字符编码集
        'port' => 3306,     //默认端口号
    ];

    //实例化Medoo类,创建db对象
    $db = new Db($config);

    //调用的函数方法
    $eidtName=isset($_GET["edit"])?$_GET["edit"]:"";
    if($eidtName=="")
    {
        return;
    }
    //获取提交过来的参数
    $arr=is_array($_POST)?$_POST:[];

    if(count($arr)>0)
    {
        //调用具体的方法并返回
        if(function_exists($eidtName))
        {
            return $eidtName($arr);
        }

    }


   //统计数量
   function count_number($table,$where){
        global $db;
        $res=$db->count($table,$where);
      return $res;
   }
   //查询指定条件的单个数据
   function find_one($table,$filed,$where){
        global $db;
        $res=$db->get($table,$filed,$where);
      return $res;
   }

   //查询所有数据
   function select($table,$field,$where){
      global $db;

        $res=$db->select($table,$field,$where);
        //$db->debug()->select($table, $field, $where);
        return $res;
   }

   //获取演员
   function getYanYuan($uid)
    {
        $res=find_one('user',['`name`','`phone`','`weight`','`height`'],['`uid`='=> $uid['uid']]);
        echo json_encode(array('info'=>$res));
    }

   //插入演员
   function insertYanYuan($arr)
    {
        global  $db;
        $arr['add_time']=time();

        //移除uid
        $arr=removeItem($arr,'uid');
        $res= $db->insert('user',$arr);

        if($res){
            echo json_encode(array('code'=>1,'text'=>'添加成功!'));
        }else{
            echo json_encode(array('code'=>0,'text'=>'添加失败!'));
        }

    }


    //更新演员
    function updateYanYuan($arr)
    {
        global  $db;
        $arr['add_time']=time();
        $where=['`uid`'=>$arr['uid']];

        //移除uid
        $arr=removeItem($arr,'uid');


        $res=$db->update('user',$arr,$where);


        if($res){
            echo json_encode(array('code'=>1,'text'=>'修改成功!'));
        }else{
            echo json_encode(array('code'=>0,'text'=>'修改失败!'));
        }

    }

    //删除演员
    function deleteYanYuan($arr)
    {
        global  $db;

        $keys=['uid'=>implode(',',array_values(explode(',',$arr['uid'])))];

        $res=$db->delete("user",["OR"=>$keys]);

        if($res){
            echo json_encode(array('code'=>1,'text'=>'删除成功!'));
        }else{
            echo json_encode(array('code'=>0,'text'=>'删除失败!'));
        }

    }

    //根据键名移除元素
    function removeItem($arr, $key){

        if(!array_key_exists($key, $arr)){

            return $arr;

        }

        $keys = array_keys($arr);

        $index = array_search($key, $keys);

        if($index !== FALSE){

            array_splice($arr, $index, 1);

        }

        return $arr;

    }
?>

config.php

<?php

require __DIR__.'/../vendorSmarty/autoload.php';

//创建smarty模板对象
$smarty=new Smarty();

//配置目录
$smarty->setTemplateDir(__DIR__ . '/../temp');    //模板目录
$smarty->setCompileDir(__DIR__.'/../temp_c');      //编译目录
$smarty->setCacheDir(__DIR__.'/../cache');          //缓存目录
$smarty->setConfigDir(__DIR__.'/../config');        //配置目录



//配置定界符:可选
$smarty -> setLeftDelimiter('{');    //变量左定界符
$smarty -> setRightDelimiter('}');  //变量右定界符

//配置缓存:可选
$smarty ->setCaching(false);               //关闭缓存
$smarty->setCacheLifetime(60*60*24);  //缓存有效时间

showTable.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>日本女演员表</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="static/js/jquery.js"></script>
    <script src="static/js/bootstrap.min.js"></script>
    <style type="text/css">

 h2
 {
            color: #666;
 }
        #tab
 {
            text-align: center;
 }
        #tab th,#tab td,#tab caption,#divTitle
 {
            text-align: center;
 padding: 8px;
 }
        #divBtn
 {
            text-align: left;
 width: 80%;
 margin: 0px auto;
 }

    </style>
</head>
<body>
{if count($rows) > 0 }
<div id="divTitle"><h2>日本女演员表</h2></div>
<div id="divBtn">
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#exampleModal" data-whatever="add">添加</button>
    <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#exampleModal" data-whatever="update" id="editYanYuan">修改</button>
    <button type="button" class="btn btn-danger btn-lg" id="delYanYuan">删除</button>
</div>
<table id="tab" border="1" cellspacing="0" align="center" width="80%">
    <caption></caption>
    <tr bgcolor="#add8e6">
        <th><input type="checkbox" id="mulSelect"/></th>
        <th>ID</th>
        <th>姓名</th>
        <th>手机号</th>
        <th>胸围</th>
        <th>身高</th>
        <th>添加时间</th>
    </tr>
 {foreach  $rows as $row}
    <tr>
        <td><input type="checkbox" name="check{$row.uid}" value="{$row.uid}"/></td>
        <td>{$row.uid}</td>
        <td>{$row.name}</td>
        <td>{$row.phone}</td>
        <td>{$row.weight}</td>
        <td>{$row.height}</td>
        <td>{$row.add_time}</td>
    </tr>
 {/foreach}
</table>
{else}
<h2 style="color:red">未能加载数据</h2>
{/if}


<!--    模态框-->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel"></h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group" style="display: none">
                        <label for="userID" class="control-label">ID:</label>
                        <input type="text" class="form-control" id="userID">
                    </div>
                    <div class="form-group">
                        <label for="userName" class="control-label">姓名:</label>
                        <input type="text" class="form-control" id="userName">
                    </div>
                    <div class="form-group">
                        <label for="userPhone" class="control-label">手机号:</label>
                        <input type="text" class="form-control" id="userPhone">
                    </div>
                    <div class="form-group">
                        <label for="userWeight" class="control-label">胸围:</label>
                        <input type="text" class="form-control" id="userWeight">
                    </div>
                    <div class="form-group">
                        <label for="userHeight" class="control-label">身高:</label>
                        <input type="text" class="form-control" id="userHeight">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="sureID"></button>
            </div>
        </div>
    </div>
</div>
</body>
</html>
<script>
 $(function(){
        // 全选按钮的勾选和取消
 $("#mulSelect").on('click', function() {
            $("input:checkbox").prop("checked", $(this).prop('checked'));
 })
        // 全选后,如果子选项有一个取消勾选,则去除全选
 $("input:checkbox").on('click', function() {
            //当选中的长度等于checkbox的长度的时候,就让控制全选反选的checkbox设置为选中,否则就为未选中
 if($("input:checkbox").length === $("input:checked").length) {
                $("#mulSelect").prop("checked", true);
 } else {
                $("#mulSelect").prop("checked", false);
 }
        })

        $("#editYanYuan").on('click', function() {
            if($('input:checked').length==0)
            {
                alert("请选择需要修改的演员");
 return;
 }
            if($('input:checked').length>1)
            {
                alert("每次只能修改一个演员");
 return;
 }
        })

        $("#delYanYuan").on('click', function() {
            if($('input:checked').length == 0)
            {
                alert("请勾选需要删除的数据");
 return;
 }

            if(!confirm("你确定要删除吗?删除后数据将不可恢复哟~~"))
            {
                return;
 }

            var uid='';
 $.each($('input:checkbox:checked'), function () {
                uid += $(this).val()+",";
 });

 uid=uid.substring(0,uid.length-1);


 $.ajax({
                type : "post",
 url : "sqlHelp.php?edit=deleteYanYuan",
 dataType : "json",
 data:{
                    uid  : uid
                },
 success : function(result){
                    alert(result.text);
 location.reload();
 },
 error:function(XMLHttpRequest){
                    alert(XMLHttpRequest.status);
 // alert(XMLHttpRequest.readyState);
 alert('添加失败,请重试!');
 }
            })

        })


        // 模态框加载事件
 $('#exampleModal').on('show.bs.modal', function (event) {

            var button = $(event.relatedTarget);
 var recipient = button.data('whatever');    //存放点击按钮是添加还是修改

            //不符合条件则直接关闭
 if(recipient!="add")
            {
                if ($('input:checked').length == 0 || $('input:checked').length > 1) {
                    $(this).close();
 }
            }

            var modal = $(this);
 var type=(recipient=="add"?"添加":"修改");
 modal.find('.modal-title').text(type+"日本女演员");  //修改模态框表头
            // modal.find('.modal-body input').val(recipient);
 modal.find('.modal-footer button[class="btn btn-primary"]').html(type);

 if(recipient!="add")
            {
                var uid = "0";
 $.each($('input:checkbox:checked'), function () {
                    uid = $(this).val();
 });

 $.ajax({
                    type: "post",
 url: "sqlHelp.php?edit=getYanYuan",
 dataType: "json",
 data: {
                        uid: uid
                    },
 success: function (result) {
                        var info = result.info;
 $("#userName").val(info.name);
 $("#userPhone").val(info.phone);
 $("#userWeight").val(info.weight);
 $("#userHeight").val(info.height);
 $("#userID").val(uid);


 },
 error: function (XMLHttpRequest) {
                        //alert(XMLHttpRequest.status);
                        // alert(XMLHttpRequest.readyState);
 alert('添加失败,请重试!');
 }
                })
            }
        })


        //模态框确认按钮点击事件
 $("#sureID").on('click', function() {
            var edit=$(this).html();

 var url="";
 if(edit=="添加")
            {
                url = "sqlHelp.php?edit=insertYanYuan";
 }
            if(edit=="修改")
            {
                url="sqlHelp.php?edit=updateYanYuan";
 }

            $.ajax({
                type : "post",
 url : url,
 dataType : "json",
 data:{
                    name  : $("#userName").val(),
 phone : $("#userPhone").val(),
 weight : $("#userWeight").val(),
 height: $("#userHeight").val(),
 uid:$("#userID").val()
                },
 success : function(result){
                    alert(result.text);
 location.reload();
 },
 error:function(XMLHttpRequest){
                    //alert(XMLHttpRequest.status);
                    // alert(XMLHttpRequest.readyState);
 alert('添加失败,请重试!');
 }
            })

        });
 })
</script>

效果如下:

QQ截图20190119141821.jpg

QQ截图20190119141835.jpg

QQ截图20190119141848.jpg

QQ截图20190119141858.jpg

批改老师:天蓬老师批改时间:2019-01-19 15:51:14
老师总结:你的表格显示的样式,是不是不太对呀, 其它还好

发布手记

热门词条