ThinkPHP菜鸟实现的增删改查

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28761593/article/details/52473151

数据库:

效果

框架:easyui




控制器代码:::::::

<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller
{

    public function index(){
        $this->display();
        $this->red();
    }

    //    +++++++++++++++++++页面显示数据+++++++++++++++++++++
    public function red(){
        $User = M('Exltable'); // 实例化Data数据模型,这行的tinyphp为数据表后缀名称
        $this->data = $User->select();


    }
//    ------------------------页面显示数据---------------

//+++++++++++++++++++添加表格+++++++++++++++++++++++++++
    public function addexl(){
        header("Content-type: text/html; charset=utf-8");

        //excel文件路径,我这里是项目根目录
        $filename = './excelfile/gjyt.xls';//表路径
        $start_row = 2;//从第二行开始读取表信息
        import("Org.Util.PHPExcel");//如果excel文件后缀名为.xls,导入这个类

        import("Org.Util.PHPExcel.Reader.Excel5");

        $php_reader = new \PHPExcel_Reader_Excel5();  //载入文件
        $filename = $this-> file_zh_cn_icvon($filename);
        $php_excel = $php_reader->load($filename);//获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推


//        循环多张sheet表
        for($sheet_index=0;$sheet_index<1;$sheet_index++){
            $currentSheet = $php_excel->getSheet($sheet_index);
            $allRow = $currentSheet->getHighestRow();

//          循环多行表格信息
            for($currentRow = $start_row;$currentRow <= $allRow;$currentRow++){
                //获取单元格的值
                $station_name = (string)$currentSheet->getCell('A'.$currentRow)->getValue();
                $station_name1 = (string)$currentSheet->getCell('B'.$currentRow)->getValue();
                $station_name2 = (string)$currentSheet->getCell('C'.$currentRow)->getValue();
                $station_name3 = (string)$currentSheet->getCell('D'.$currentRow)->getValue();
                $station_name4 = (string)$currentSheet->getCell('E'.$currentRow)->getValue();

//                ++++++++++++++++++添加表数据++++++++++++++++

                    $User = M("Exltable");

                    $data['exl_usname'] = $station_name;
                    $data['exl_chname'] =$station_name1;
                    $data['exl_usurl'] =$station_name2;
                    $data['exl_churl'] =$station_name3;
                    $data['exl_text'] =$station_name4;
                    $sql= $User->add($data);

                    if(!$sql){
                        $result = $User->add(); // 写入数据到数据库
                        if($result){
                            // 如果主键是自动增长型 成功后返回值就是最新插入的值
                            $insertId = $result;
                            $this->display();
                        }
                    }

//      ------------------添加表数据-----------------------
                ob_flush();
                flush();
            }
        }

    }
//——————————————添加表格——————————————————

    function file_zh_cn_icvon($filename){
        //windows环境下,文件名最好是有GBK转化为utf-8
        if(IS_WIN){
            return iconv('UTF-8', 'GBK', $filename);
        }
        return $filename;
    }


//    ++++++++++++++++++++++++添加数据++++++++++++++++

    public function edit(){


        if(IS_POST){
            $User = M("Exltable"); // 实例化User对象
            $data['exl_usname'] = I('post.usname');
            $data['exl_chname'] =I('post.chname');
            $data['exl_usurl'] =I('post.usurl');
            $data['exl_churl'] =I('post.churl');
            $data['exl_text'] =I('post.text');

            $Urls=$User->select();

            foreach ($Urls as $val){
                $usname=$val["exl_usname"];
                $pname=$data['exl_usname'];
            }
            if($usname != $pname){
                $result= $User->add($data);
            }
            else if($pname==null){
                $this->error('没有填写数据 ');
            }


            if($data){

                if($result){
                    // 如果主键是自动增长型 成功后返回值就是最新插入的值
                    $insertId = $result;
                    $this->redirect('/Home/Index/index',0);

                }else{
                    //错误页面的默认跳转页面是返回前一页,通常不需要设置
                    $this->error('已经有该名称');
                }
            }

        }
        else if(IS_GET){
            $this->display('index:index');
        }
    }
//    ------------------------添加数据-----------------

//    ++++++++++++++++++++++++删除数据++++++++++++++++
    public function delete(){

        $Test = M('Exltable');
        $ids = implode(",", I('post.ids'));
        $Test->delete($ids);

    }
//    ------------------------删除数据-----------------


//++++++++++++++++++++修改数据+++++++++++++++++++
    public function test()
    {
        $this->display('user:ajax');
    }
    public  function testcav(){
        $User = M("Exltable");
        if (IS_GET) {
            $id = I('get.id');
            $map['exl_id'] = array('eq', $id);
            $obj = $User->where($map)->find();
            echo json_encode($obj);
        }
        if(IS_POST){
            $data['exl_id']=  I('post.exl_id');
            $data['exl_usname'] = I('post.exl_usname');
            $data['exl_chname'] = I('post.exl_chname');
            $data['exl_usurl'] = I('post.exl_usurl');
            $data['exl_churl'] = I('post.exl_churl');
            $data['exl_text'] = I('post.exl_text');
            $result= $User->save($data);
            if($result){
                // 如果主键是自动增长型 成功后返回值就是最新插入的值
                $insertId = $result;
                $this->redirect('/Home/Index/index',0);
            }else{
                $this->error('没有填写信息',0);
            }
        }
    }
//--------------------修改数据-----------------


//++++++++++++++++++++查询++++++++++++++++++++++++++

//thinkphp 查询语言
//         1.普通查询
//   2.区间查询
//   3.组合查询
//   4.复合查询
//   5.统计查询
//   6.定位查询
//   7.SQL查询
//   8.动态查询
    public function sele(){

        if(IS_POST){
            $User=M('Exltable');

            $condition['exl_usname'] = array('like', '%'.I('post.exl_usname').'%');
            $condition['exl_chname'] = array('like', '%'.I('post.exl_chname').'%');
            $condition['exl_usurl'] = array('like', '%'.I('post.exl_usurl').'%');
            $condition['exl_churl'] = array('like', '%'.I('post.exl_churl').'%');
            $condition['exl_text'] = array('like', '%'.I('post.exl_text').'%');





            //查询数据库,数据存在输出。数据不存在,反馈信息
            $count = $User->where($condition)->count();
            $obj =$User->where($condition)->select();

            echo json_encode(array('total'=>$count, 'rows'=>$obj));

//            $userarr = $User->select();
//             var_dump($userarr);
//            $this->assign("userarr",$userarr);

        }
        else if(IS_GET){

        }





    }

//----------------------查询-------------------------
//++++++++++++++++分页++++++++++++++++++++++
    public function get_all(){
        $list = get_date_grid('Exltable');//Exltabl数据库表名称
        echo json_encode($list);
    }
//----------------分页------------------------

//-----------------------------------------------------------------------------


}

前台hrml代码:::::::::::::::::::::::::::::;

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Basic DataGrid - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/jquery-easyui-1.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/jquery-easyui-1.5/themes/icon.css">
    <script type="text/javascript" src="__PUBLIC__/jquery-easyui-1.5/jquery.min.js"></script>
    <script type="text/javascript" src="__PUBLIC__/jquery-easyui-1.5/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="__PUBLIC__/jquery-easyui-1.5/locale/easyui-lang-zh_CN.js" charset="utf-8"></script>
    <style>

    </style>
</head>
<body>
<style>
    .select{ display: none; background: rgba(0,0,0,0.5);  padding: 15px 20px;}
</style>
<!--表单-->
<div id="" action="" method="" >


    <div style="">
        <div id="tb" style="padding:2px 5px;">
            <a href="javascript:void(0)" id="uplod"  class="easyui-linkbutton" iconCls="icon-add" plain="true" onClick="uplod()">添加表信息</a>
            <a href="javascript:void(0)" id="openwin"  class="easyui-linkbutton" iconCls="icon-add" plain="true" onClick="addPro()"></a>
            <a href="javascript:void(0)" id="updaten" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editPro()"></a>
            <a href="javascrtpt:void(0)" id="grid_pump_log" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removePro()"></a>
            <a href="javascript:void(0)" id="select" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true"></a>
            <form action="__URL__/sele" class="select"  method="post">
                <input type="text" name="exl_usname" id="exl_usname" placeholder="英文名称"/>
                <input type="text" name="exl_chname"  id="exl_chname" placeholder="中文名称"/>
                <input type="text" name="exl_usurl"  id="exl_usurl" placeholder="英文路径"/>
                <input type="text" name="exl_churl"  id="exl_churl" placeholder="中文路径"/>
                <input type="text" name="exl_text"  id="exl_text" placeholder="功能用途"/>
                <input type="button" id="selectinput" value="查询" name="" />
            </form>

        </div>
        <!--查询-->

    </div>
    <table id="dg" title="数据表" style="width:100%;" data-options="rownumbers:true">
    </table>

</div>


<!--添加-->
<form method="post"  id="win" class="easyui-window" title="添加数据" closed="true" style="width:600px;height:400px"
      data-options="rownumbers:true,singleSelect:true,pagination:true,url:'datagrid_data1.json',method:'get'"
      action="__URL__/edit";>


    <div class="easyui-layout" data-options="fit:true" >
        <ul data-options="region:'north',split:true" style="height:200px">
            <li>
                英文名称:<input type="text" value="" name="usname"/>
            </li>
            <li>
                中文名称:<input type="text" value="" name="chname"/>
            </li>
            <li>
                英文路径:<input type="text" value="" name="usurl"/>
            </li>
            <li>
                中文路径:<input type="text" value="" name="churl"/>
            </li>
            <li>
                功能用途:<textarea type="text" value="" name="text" ></textarea>
            </li>
            <li>
                <input type="submit" name=""/>
            </li>
        </ul>
    </div>
</form>

<!--修改-->
<form  method="post"  id="formsav" action="__URL__/testcav" class="easyui-window" title="修改数据" closed="true" style="width:600px;height:400px">
    <div data-options="fit:true" >
        <ul  style="height:200px"  data-options="region:'north',split:true" style="height:200px"   name="upsav" id="sav">
            <input type="text" value="" style="display: none" name="exl_id" />
            <li>英文名称:<input type="text" value="" name="exl_usname" /></li>
            <li>中文名称:<input type="text" value="" name="exl_chname" /></li>
            <li>英文路径:<input type="text" value="" name="exl_usurl"  /></li>
            <li>中文路径:<input type="text" value="" name="exl_churl" /></li>
            <li>功能用途:<textarea type="text" value="" name="exl_text" ></textarea></li>
            <li><input type="submit"  id="upsav" name="" /></li>
        </ul>
    </div>
</form>

<script type="text/javascript">

//修改
    function editPro(){
        var row = $("#dg").datagrid("getSelected");
        if(row){
            $("#formsav").dialog("open").dialog("setTitle","修改");
            $("#am").form("load",row);
            var data = {'exlid': row.exl_id};
            var id= row.exl_id;
            $.ajax({
                type:"get",
                url:"__URL__/testcav",
                data:{id:id},
                dataType:"json",

                success:function(json, textStatus){
                    $('#formsav').form('load',{
                        "exl_id": json.exl_id,
                        "exl_usname": json.exl_usname,
                        "exl_chname": json.exl_chname,
                        "exl_usurl":json.exl_usurl,
                        "exl_churl":json.exl_churl,
                        "exl_text": json.exl_text
                    });

                },error:function(XMLHttpRequest, textStatus, errorThrown)
                {
                    relogin(XMLHttpRequest, textStatus, errorThrown);
                }});
        }
    }
//删除
    function removePro() {
        var row = $('#dg').datagrid('getSelected');
        if (row) {
            $.messager.confirm(
                    '提示',
                    '确定删除该数据吗?',
                    function (r) {
                    if (r) {
                        var ids = [];//定义一个数组用于存储选中的删除项
                        var rows = $('#dg').datagrid('getSelections');
                        for (var i = 0; i < rows.length; i++) {
                            ids.push(rows[i].exl_id);
                        }
                        //获取id
    //                    console.log(ids);
                        var data = {'ids': ids};
                        $.post(
                                url = "{:U('Index/delete')}",//删除方法路径
                                data,
                                function (msg) {
                                    $('#dg').datagrid({
                                        url:'__URL__/get_all',
                                        queryParams:{page:1,rows:20}
                                        });
                                }
                        );
                    }
            });
        }
    }

//    搜索
    $("#select").click(function(){
        $(".select").toggle();
    });

    $("#selectinput").click(function(){
        var exl_usname = $('#exl_usname').val();
        var exl_chname = $('#exl_chname').val();
        var exl_usurl = $('#exl_usurl').val();
        var exl_churl = $('#exl_churl').val();
        var exl_text = $('#exl_text').val();
        $('#dg').datagrid({
            url:'__URL__/get_all',
            queryParams:{
                page:1,rows:20,
                'exl_usname':exl_usname,
                'exl_chname':exl_chname,
                'exl_usurl':exl_usurl,
                'exl_churl':exl_churl,
                'exl_text':exl_text
            }
        });

    })

</script>
<script>
//    打开窗口
    $( "#openwin" ).click(function() {
        $('#win').window('open');
    });
    $( "#updaten" ).click(function() {
        $('#form').window('open'); // close a window
    });

</script>

<script type="text/javascript">
//数据加载表格
    $('#dg').datagrid({
        url:'__URL__/get_all',//从远程站点请求数据的数据地址。
        queryParams:{page:1,rows:20},
        pagination:true,//设置为 true,在数据网格(datagrid)底部显示分页工具栏。
        method:'get',//请求远程数据的方法类型get/post。
        pageSize:30,//默认每页显示个数
            columns:[[//列(Column)属性

            {field:'exl_usname',title:'英文名称',width:100},
            {field:'exl_chname',title:'中文名称',width:100},
            {field:'exl_usurl',title:'英文路径',width:150},
            {field:'exl_churl',title:'中文路径',width:200},
            {field:'exl_text',title:'用途',width:400},
        ]]
    });
</script>
</body>
</html>

菜鸟不会啊:还是有收获的,


common/common/function.php文件内容

<?php
/**
 * Created by PhpStorm.
 * User: insist
 * Date: 2016/8/31
 * Time: 14:18
 */
function get_date_grid($model_name){
    $model = D($model_name);
    $map = array_merge(get_page_query_map(I('get.')), get_page_query_map(I('post.')));
    $page = max(I('get.page'), 1);
//    $rows_num = I('get.rows')?I('get.rows'):20;
    $rows_num = I('get.rows');
    $obj = $model->get_list_use_page($map, $page, $rows_num);
    return array('total'=>$obj['total'], 'rows'=>$obj['list'], 'map'=> $obj['map']);
}

function get_page_query_map($array){
    if(!isset($array)||!$array){
        $array = array();
    }
    //默认采用like
    //保留分页key为‘p’
    unset($array['page']);
    unset($array['rows']);
    $map = array();
    foreach($array as $k => $v){
        $map[$k] = array('like', "%$v%");
    }
    return $map;
}

function filter_query_map($map = array()){
    $temp = array();
    unset($map['sort']);
    unset($map['order']);
    foreach($map as $k => $v){
        if($v[1]!='%%'&&$v[1]!=''){
            $temp[$k] = $v;
        }
    }
    return $temp;
}





猜你喜欢

转载自blog.csdn.net/qq_28761593/article/details/52473151