1、easyUI-创建 CRUD普通dataGrid(表格)

在实现功能之前,我们要做以下几个准备:

分以下几个步骤:开发工具,easyUI包,目录结构,创建数据库,创建相应的页面视图,后台代码编写,优化;

第一步:开发工具

  我的开发工具是Hbuild,开发语言是PHP,开发数据库是MySQL,服务器是Apache;

  HBuilder。HBuilder开发工具可以在官网下载最新版本工具:http://www.dcloud.io/下载;

  WampServer开发环境下载。http://wampserver-64bit.en.softonic.com/。选择三合一,既PHP,MYSQL,APACHE;

  安装:

  ①HBuilder下载后直接解压使用无需安装。

  ②WampServer下载后按步骤安装即可,安装后自带Mysql,Apache服务器和PHP环境,有一键启动服务等功能,不需要额外下载数据库和apche或tomcat来装载服务,非常方便。(如果安装有问题的话,下载vcredist_x86.exe文件,在安装WampServer之前安装)。

  ③下载mysql图形画界面。(可有可无,不熟悉命令行操作,最好下载)。

第二步:easyUI包

  下载最新版本easyUI包,在官网下载;

  解压后如图所示:

  

第三步:目录结构

  下载好后相关工具文件等,打开Hbuild工具

  目录如下:

  

  创建后的目录介绍,空项目只有,app目录,css,js,img,index.php,index.html;

  我们加入了几个文件目录,data目录,主要存放Action或后台操作文件,model目录主要存放后台具体实现方法,page主要存放页面(采用mvc模式建立),common目录

  主要存放一些公用的文件,新建的UI目录,主要放一些插件UI如easyUI包。

第四步:创建数据库

  我们示例为增删改查用户,所以我们创建一个eui_user表

CREATE TABLE `eui_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) DEFAULT NULL,
  `lname` varchar(255) DEFAULT NULL,
  `sex` varchar(255) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

第五步:创建相应的页面视图

  1、首先,在启用服务器的时候,首先找的是index.html,所有我们编辑html让其跳转我我们的index.php入口,代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta http-equiv="refresh" content="0;URL=app/index.php"><!--加入这行代码就会跳转到index.php -->
    </head>
    <body>

    </body>
</html>

  2、引入相关的easyUI的js,在index.php中,如图所示:

  

  3、创建没有 javascript 代码的 DataGrid来显示用户,即用户列表。如代码:

  

<table id="dg" title="用户列表" class="easyui-datagrid" style="width:550px;height:250px" url="./data/crud/get_user.php" toolbar="#toolbar" rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50"></th>
                <th field="lname" width="50"></th>
                <th field="sex" width="50">性别</th>
                <th field="phone" width="50">联系电话</th>
                <th field="email" width="50">邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">修改</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteUser()">删除</a>
    </div>

table的一些属性大家可以查看easyUI的API,这里皆不解释了,我们要注意的是这个属性url,直接在table里面当做属性使用会自动请求这个地址,

编写get_user.php,如下代码:在代码中看到引入文件在common目录下,稍后会附出,里面主要编写了一些关于操作数据库的方法。

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    $medoo = new medoo();
    $result = $medoo->select("eui_user","*");
    echo json_encode($result,JSON_UNESCAPED_UNICODE);
    

 运行结果如图:(里面有数据) 

 4、我们使用相同的对话框来创建或编辑用户。即点击添加,修改按钮用的都是同一套代码,用弹出框形式操作,如页面代码:

<div id="dlg" class="easyui-dialog" style="width:400px;height:320px;padding:10px 20px;" closed="true" buttons="#dlg-buttons">
        <div class="ftitle">基本信息</div>
        <hr />
        <form id="fm" method="post">
            <div class="fitem">
                <p>
                    <label>First Name:</label>
                    <input name="fname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Last Name:</label>
                    <input name="lname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Sex:</label>
                    <input name="sex" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Phone:</label>
                    <input name="phone">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Email:</label>
                    <input name="email" class="easyui-validatebox" validType="email">
                </p>
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    </div>

  4、看到一些onclick属性,里面的方法就是我们要实现的,所以我们首先建一个js文件如2所示的js,

    首先newUser实现:在js中编写如下代码:

//添加用户
function newUser(){
    $('#dlg').dialog('open').dialog('setTitle','添加用户');
    $('#fm').form('clear');
    url = './data/crud/save_user.php?flag=add';
}

  弹出如图编辑界面:

  实现保存方法saveUser,代码如下:

//保存用户
function saveUser(){
    $('#fm').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(result){
            //alert(result);
            var result = eval('('+result+')');
            if (result.errorMsg){
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                $('#dlg').dialog('close');        // close the dialog
                $('#dg').datagrid('reload');    // reload the user data
            }
        }
    });
}

请求的地址,就是要编写后台代码,此处不解释。

整个js文件如下(不一一解释):

/*
 * crud   用户部分
 */
//添加用户
function newUser(){
    $('#dlg').dialog('open').dialog('setTitle','添加用户');
    $('#fm').form('clear');
    url = './data/crud/save_user.php';
}
//修改用户
function editUser(){
    var row = $('#dg').datagrid('getSelected');
    if (row){
        $('#dlg').dialog('open').dialog('setTitle','修改用户');
        $('#fm').form('load',row);
        url = './data/crud/edit_user.php?id='+row.id;
    }
}

//保存用户
function saveUser(){
    $('#fm').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(result){
            //alert(result);
            var result = eval('('+result+')');
            if (result.errorMsg){
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                $('#dlg').dialog('close');        // close the dialog
                $('#dg').datagrid('reload');    // reload the user data
            }
        }
    });
}
//删除用户
function deleteUser(){
    var row = $('#dg').datagrid('getSelected');
    var url = './data/crud/delete_user.php';
    if(row){
            $.messager.confirm('Confirm','你确定要删除【'+row.lname+row.fname+'】么?',function(r){
            if (r){
                $.post(url,{id:row.id},function(result){
                    if (result.success){
                        $('#dg').datagrid('reload');    // reload the user data
                    } else {
                        $.messager.show({    // show error message
                            title: 'Error',
                            msg: result.errorMsg
                        });
                    }
                },'json');
            }
        });
    }
}

第六步:后台代码编写

列表代码(get_user.php):

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    $medoo = new medoo();
    $result = $medoo->select("eui_user","*");
    echo json_encode($result,JSON_UNESCAPED_UNICODE);
    

保存代码(save_user.php):

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    $medoo = new medoo();
    $arrayName = array($_POST);
    $result = $medoo->insert("eui_user",$arrayName);
    if($result){
        echo json_encode(array('success'=>true));
    }else{
        echo json_encode(array('msg'=>'Some errors occured.'));
    }
    

修改代码(edit_user.php):

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    $medoo = new medoo();
    $id = $_GET['id'];
    $result = $medoo->update("eui_user",$_POST," where id=".$id);
    if($result){
        echo json_encode(array('success'=>true));
    }else{
        echo json_encode(array('msg'=>'Some errors occured.'));
    }
    

删除代码(delete_user.php):

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    $medoo = new medoo();
    $id = $_POST['id'];
    $result = $medoo->delete("eui_user"," where id=".$id);
    if($result){
        echo json_encode(array('success'=>true));
    }else{
        echo json_encode(array('msg'=>'Some errors occured.'));
    }

第七步:优化

  在这些过程中,我们可以把这些增删改查都放在一个文件中,优化后的代码如下,(前面的文件都不要),重新来过,

首先附上common下的medoo文件(此文件直接拿来用,不需要过于深入,只需知道怎么用它即可)

medoo.php

<?php
/*!
 * Medoo database framework
 * http://medoo.in
 * Version 0.9.8.2
 *
 * Copyright 2015, Angel Lai
 * Released under the MIT license
 */
class medoo
{
    // General
    protected $database_type = 'MySQL';

    protected $charset = 'utf8';

    protected $database_name = 'easyui';

    // For MySQL, MariaDB, MSSQL, Sybase, PostgreSQL, Oracle
    protected $server = 'localhost';

    protected $username = 'root';

    protected $password = '';

    // For SQLite
    protected $database_file;

    // For MySQL or MariaDB with unix_socket
    protected $socket;

    // Optional
    protected $port = 3306;

    protected $option = array();

    // Variable
    protected $logs = array();

    protected $debug_mode = false;

    public function __construct($options = null)
    {
        try {
            $commands = array();

            if (is_string($options) && !empty($options))
            {
                if (strtolower($this->database_type) == 'sqlite')
                {
                    $this->database_file = $options;
                }
                else
                {
                    $this->database_name = $options;
                }
            }
            elseif (is_array($options))
            {
                foreach ($options as $option => $value)
                {
                    $this->$option = $value;
                }
            }

            if (
                isset($this->port) &&
                is_int($this->port * 1)
            )
            {
                $port = $this->port;
            }

            $type = strtolower($this->database_type);
            $is_port = isset($port);

            switch ($type)
            {
                case 'mariadb':
                    $type = 'mysql';

                case 'mysql':
                    if ($this->socket)
                    {
                        $dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
                    }
                    else
                    {
                        $dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
                    }

                    // Make MySQL using standard quoted identifier
                    $commands[] = 'SET SQL_MODE=ANSI_QUOTES';
                    break;

                case 'pgsql':
                    $dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
                    break;

                case 'sybase':
                    $dsn = 'dblib:host=' . $this->server . ($is_port ? ':' . $port : '') . ';dbname=' . $this->database_name;
                    break;

                case 'oracle':
                    $dbname = $this->server ?
                        '//' . $this->server . ($is_port ? ':' . $port : ':1521') . '/' . $this->database_name :
                        $this->database_name;

                    $dsn = 'oci:dbname=' . $dbname . ($this->charset ? ';charset=' . $this->charset : '');
                    break;

                case 'mssql':
                    $dsn = strstr(PHP_OS, 'WIN') ?
                        'sqlsrv:server=' . $this->server . ($is_port ? ',' . $port : '') . ';database=' . $this->database_name :
                        'dblib:host=' . $this->server . ($is_port ? ':' . $port : '') . ';dbname=' . $this->database_name;

                    // Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting
                    $commands[] = 'SET QUOTED_IDENTIFIER ON';
                    break;

                case 'sqlite':
                    $dsn = $type . ':' . $this->database_file;
                    $this->username = null;
                    $this->password = null;
                    break;
            }

            if (
                in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) &&
                $this->charset
            )
            {
                $commands[] = "SET NAMES '" . $this->charset . "'";
            }

            $this->pdo = new PDO(
                $dsn,
                $this->username,
                $this->password,
                $this->option
            );

            foreach ($commands as $value)
            {
                $this->pdo->exec($value);
            }
        }
        catch (PDOException $e) {
            throw new Exception($e->getMessage());
        }
    }

    public function query($query)
    {
        if ($this->debug_mode)
        {
            echo $query;

            $this->debug_mode = false;

            return false;
        }

        array_push($this->logs, $query);

        return $this->pdo->query($query);
    }

    public function exec($query)
    {
        if ($this->debug_mode)
        {
            echo $query;

            $this->debug_mode = false;

            return false;
        }

        array_push($this->logs, $query);

        return $this->pdo->exec($query);
    }

    public function quote($string)
    {
        return $this->pdo->quote($string);
    }

    protected function column_quote($string)
    {
        return '"' . str_replace('.', '"."', preg_replace('/(^#|\(JSON\))/', '', $string)) . '"';
    }

    protected function column_push($columns)
    {
        if ($columns == '*')
        {
            return $columns;
        }

        if (is_string($columns))
        {
            $columns = array($columns);
        }

        $stack = array();

        foreach ($columns as $key => $value)
        {
            preg_match('/([a-zA-Z0-9_\-\.]*)\s*\(([a-zA-Z0-9_\-]*)\)/i', $value, $match);

            if (isset($match[1], $match[2]))
            {
                array_push($stack, $this->column_quote( $match[1] ) . ' AS ' . $this->column_quote( $match[2] ));
            }
            else
            {
                array_push($stack, $this->column_quote( $value ));
            }
        }

        return implode($stack, ',');
    }

    protected function array_quote($array)
    {
        $temp = array();

        foreach ($array as $value)
        {
            $temp[] = is_int($value) ? $value : $this->pdo->quote($value);
        }

        return implode($temp, ',');
    }

    protected function inner_conjunct($data, $conjunctor, $outer_conjunctor)
    {
        $haystack = array();

        foreach ($data as $value)
        {
            $haystack[] = '(' . $this->data_implode($value, $conjunctor) . ')';
        }

        return implode($outer_conjunctor . ' ', $haystack);
    }

    protected function fn_quote($column, $string)
    {
        return (strpos($column, '#') === 0 && preg_match('/^[A-Z0-9\_]*\([^)]*\)$/', $string)) ?

            $string :

            $this->quote($string);
    }

    protected function data_implode($data, $conjunctor, $outer_conjunctor = null)
    {
        $wheres = array();

        foreach ($data as $key => $value)
        {
            $type = gettype($value);

            if (
                preg_match("/^(AND|OR)\s*#?/i", $key, $relation_match) &&
                $type == 'array'
            )
            {
                $wheres[] = 0 !== count(array_diff_key($value, array_keys(array_keys($value)))) ?
                    '(' . $this->data_implode($value, ' ' . $relation_match[1]) . ')' :
                    '(' . $this->inner_conjunct($value, ' ' . $relation_match[1], $conjunctor) . ')';
            }
            else
            {
                preg_match('/(#?)([\w\.]+)(\[(\>|\>\=|\<|\<\=|\!|\<\>|\>\<|\!?~)\])?/i', $key, $match);
                $column = $this->column_quote($match[2]);

                if (isset($match[4]))
                {
                    $operator = $match[4];

                    if ($operator == '!')
                    {
                        switch ($type)
                        {
                            case 'NULL':
                                $wheres[] = $column . ' IS NOT NULL';
                                break;

                            case 'array':
                                $wheres[] = $column . ' NOT IN (' . $this->array_quote($value) . ')';
                                break;

                            case 'integer':
                            case 'double':
                                $wheres[] = $column . ' != ' . $value;
                                break;

                            case 'boolean':
                                $wheres[] = $column . ' != ' . ($value ? '1' : '0');
                                break;

                            case 'string':
                                $wheres[] = $column . ' != ' . $this->fn_quote($key, $value);
                                break;
                        }
                    }

                    if ($operator == '<>' || $operator == '><')
                    {
                        if ($type == 'array')
                        {
                            if ($operator == '><')
                            {
                                $column .= ' NOT';
                            }

                            if (is_numeric($value[0]) && is_numeric($value[1]))
                            {
                                $wheres[] = '(' . $column . ' BETWEEN ' . $value[0] . ' AND ' . $value[1] . ')';
                            }
                            else
                            {
                                $wheres[] = '(' . $column . ' BETWEEN ' . $this->quote($value[0]) . ' AND ' . $this->quote($value[1]) . ')';
                            }
                        }
                    }

                    if ($operator == '~' || $operator == '!~')
                    {
                        if ($type == 'string')
                        {
                            $value = array($value);
                        }

                        if (!empty($value))
                        {
                            $like_clauses = array();

                            foreach ($value as $item)
                            {
                                if ($operator == '!~')
                                {
                                    $column .= ' NOT';
                                }

                                if (preg_match('/^(?!%).+(?<!%)$/', $item))
                                {
                                    $item = '%' . $item . '%';
                                }

                                $like_clauses[] = $column . ' LIKE ' . $this->fn_quote($key, $item);
                            }

                            $wheres[] = implode(' OR ', $like_clauses);
                        }
                    }

                    if (in_array($operator, array('>', '>=', '<', '<=')))
                    {
                        if (is_numeric($value))
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $value;
                        }
                        elseif (strpos($key, '#') === 0)
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $this->fn_quote($key, $value);
                        }
                        else
                        {
                            $wheres[] = $column . ' ' . $operator . ' ' . $this->quote($value);
                        }
                    }
                }
                else
                {
                    switch ($type)
                    {
                        case 'NULL':
                            $wheres[] = $column . ' IS NULL';
                            break;

                        case 'array':
                            $wheres[] = $column . ' IN (' . $this->array_quote($value) . ')';
                            break;

                        case 'integer':
                        case 'double':
                            $wheres[] = $column . ' = ' . $value;
                            break;

                        case 'boolean':
                            $wheres[] = $column . ' = ' . ($value ? '1' : '0');
                            break;

                        case 'string':
                            $wheres[] = $column . ' = ' . $this->fn_quote($key, $value);
                            break;
                    }
                }
            }
        }

        return implode($conjunctor . ' ', $wheres);
    }

    protected function where_clause($where)
    {
        $where_clause = '';

        if (is_array($where))
        {
            $where_keys = array_keys($where);
            $where_AND = preg_grep("/^AND\s*#?$/i", $where_keys);
            $where_OR = preg_grep("/^OR\s*#?$/i", $where_keys);

            $single_condition = array_diff_key($where, array_flip(
                explode(' ', 'AND OR GROUP ORDER HAVING LIMIT LIKE MATCH')
            ));

            if ($single_condition != array())
            {
                $where_clause = ' WHERE ' . $this->data_implode($single_condition, '');
            }

            if (!empty($where_AND))
            {
                $value = array_values($where_AND);
                $where_clause = ' WHERE ' . $this->data_implode($where[ $value[0] ], ' AND');
            }

            if (!empty($where_OR))
            {
                $value = array_values($where_OR);
                $where_clause = ' WHERE ' . $this->data_implode($where[ $value[0] ], ' OR');
            }

            if (isset($where['MATCH']))
            {
                $MATCH = $where['MATCH'];

                if (is_array($MATCH) && isset($MATCH['columns'], $MATCH['keyword']))
                {
                    $where_clause .= ($where_clause != '' ? ' AND ' : ' WHERE ') . ' MATCH ("' . str_replace('.', '"."', implode($MATCH['columns'], '", "')) . '") AGAINST (' . $this->quote($MATCH['keyword']) . ')';
                }
            }

            if (isset($where['GROUP']))
            {
                $where_clause .= ' GROUP BY ' . $this->column_quote($where['GROUP']);

                if (isset($where['HAVING']))
                {
                    $where_clause .= ' HAVING ' . $this->data_implode($where['HAVING'], ' AND');
                }
            }

            if (isset($where['ORDER']))
            {
                $rsort = '/(^[a-zA-Z0-9_\-\.]*)(\s*(DESC|ASC))?/';
                $ORDER = $where['ORDER'];

                if (is_array($ORDER))
                {
                    if (
                        isset($ORDER[1]) &&
                        is_array($ORDER[1])
                    )
                    {
                        $where_clause .= ' ORDER BY FIELD(' . $this->column_quote($ORDER[0]) . ', ' . $this->array_quote($ORDER[1]) . ')';
                    }
                    else
                    {
                        $stack = array();

                        foreach ($ORDER as $column)
                        {
                            preg_match($rsort, $column, $order_match);

                            array_push($stack, '"' . str_replace('.', '"."', $order_match[1]) . '"' . (isset($order_match[3]) ? ' ' . $order_match[3] : ''));
                        }

                        $where_clause .= ' ORDER BY ' . implode($stack, ',');
                    }
                }
                else
                {
                    preg_match($rsort, $ORDER, $order_match);

                    $where_clause .= ' ORDER BY "' . str_replace('.', '"."', $order_match[1]) . '"' . (isset($order_match[3]) ? ' ' . $order_match[3] : '');
                }
            }

            if (isset($where['LIMIT']))
            {
                $LIMIT = $where['LIMIT'];

                if (is_numeric($LIMIT))
                {
                    $where_clause .= ' LIMIT ' . $LIMIT;
                }

                if (
                    is_array($LIMIT) &&
                    is_numeric($LIMIT[0]) &&
                    is_numeric($LIMIT[1])
                )
                {
                    if ($this->database_type === 'pgsql')
                    {
                        $where_clause .= ' OFFSET ' . $LIMIT[0] . ' LIMIT ' . $LIMIT[1];
                    }
                    else
                    {
                        $where_clause .= ' LIMIT ' . $LIMIT[0] . ',' . $LIMIT[1];
                    }
                }
            }
        }
        else
        {
            if ($where != null)
            {
                $where_clause .= ' ' . $where;
            }
        }

        return $where_clause;
    }

    protected function select_context($table, $join, &$columns = null, $where = null, $column_fn = null)
    {
        $table = '"' . $table . '"';
        $join_key = is_array($join) ? array_keys($join) : null;

        if (
            isset($join_key[0]) &&
            strpos($join_key[0], '[') === 0
        )
        {
            $table_join = array();

            $join_array = array(
                '>' => 'LEFT',
                '<' => 'RIGHT',
                '<>' => 'FULL',
                '><' => 'INNER'
            );

            foreach($join as $sub_table => $relation)
            {
                preg_match('/(\[(\<|\>|\>\<|\<\>)\])?([a-zA-Z0-9_\-]*)\s?(\(([a-zA-Z0-9_\-]*)\))?/', $sub_table, $match);

                if ($match[2] != '' && $match[3] != '')
                {
                    if (is_string($relation))
                    {
                        $relation = 'USING ("' . $relation . '")';
                    }

                    if (is_array($relation))
                    {
                        // For ['column1', 'column2']
                        if (isset($relation[0]))
                        {
                            $relation = 'USING ("' . implode($relation, '", "') . '")';
                        }
                        else
                        {
                            $joins = array();

                            foreach ($relation as $key => $value)
                            {
                                $joins[] = (
                                    strpos($key, '.') > 0 ?
                                        // For ['tableB.column' => 'column']
                                        '"' . str_replace('.', '"."', $key) . '"' :

                                        // For ['column1' => 'column2']
                                        $table . '."' . $key . '"'
                                ) .
                                ' = ' .
                                '"' . (isset($match[5]) ? $match[5] : $match[3]) . '"."' . $value . '"';
                            }

                            $relation = 'ON ' . implode($joins, ' AND ');
                        }
                    }

                    $table_join[] = $join_array[ $match[2] ] . ' JOIN "' . $match[3] . '" ' . (isset($match[5]) ?  'AS "' . $match[5] . '" ' : '') . $relation;
                }
            }

            $table .= ' ' . implode($table_join, ' ');
        }
        else
        {
            if (is_null($columns))
            {
                if (is_null($where))
                {
                    if (
                        is_array($join) &&
                        isset($column_fn)
                    )
                    {
                        $where = $join;
                        $columns = null;
                    }
                    else
                    {
                        $where = null;
                        $columns = $join;
                    }
                }
                else
                {
                    $where = $join;
                    $columns = null;
                }
            }
            else
            {
                $where = $columns;
                $columns = $join;
            }
        }

        if (isset($column_fn))
        {
            if ($column_fn == 1)
            {
                $column = '1';

                if (is_null($where))
                {
                    $where = $columns;
                }
            }
            else
            {
                if (empty($columns))
                {
                    $columns = '*';
                    $where = $join;
                }

                $column = $column_fn . '(' . $this->column_push($columns) . ')';
            }
        }
        else
        {
            $column = $this->column_push($columns);
        }

        return 'SELECT ' . $column . ' FROM ' . $table . $this->where_clause($where);
    }

    public function select($table, $join, $columns = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $columns, $where));

        return $query ? $query->fetchAll(
            (is_string($columns) && $columns != '*') ? PDO::FETCH_COLUMN : PDO::FETCH_ASSOC
        ) : false;
    }

    public function insert($table, $datas)
    {
        $lastId = array();

        // Check indexed or associative array
        if (!isset($datas[0]))
        {
            $datas = array($datas);
        }

        foreach ($datas as $data)
        {
            $values = array();
            $columns = array();

            foreach ($data as $key => $value)
            {
                array_push($columns, $this->column_quote($key));

                switch (gettype($value))
                {
                    case 'NULL':
                        $values[] = 'NULL';
                        break;

                    case 'array':
                        preg_match("/\(JSON\)\s*([\w]+)/i", $key, $column_match);

                        $values[] = isset($column_match[0]) ?
                            $this->quote(json_encode($value)) :
                            $this->quote(serialize($value));
                        break;

                    case 'boolean':
                        $values[] = ($value ? '1' : '0');
                        break;

                    case 'integer':
                    case 'double':
                    case 'string':
                        $values[] = $this->fn_quote($key, $value);
                        break;
                }
            }

            $this->exec('INSERT INTO "' . $table . '" (' . implode(', ', $columns) . ') VALUES (' . implode($values, ', ') . ')');

            $lastId[] = $this->pdo->lastInsertId();
        }

        return count($lastId) > 1 ? $lastId : $lastId[ 0 ];
    }

    public function update($table, $data, $where = null)
    {
        $fields = array();

        foreach ($data as $key => $value)
        {
            preg_match('/([\w]+)(\[(\+|\-|\*|\/)\])?/i', $key, $match);

            if (isset($match[3]))
            {
                if (is_numeric($value))
                {
                    $fields[] = $this->column_quote($match[1]) . ' = ' . $this->column_quote($match[1]) . ' ' . $match[3] . ' ' . $value;
                }
            }
            else
            {
                $column = $this->column_quote($key);

                switch (gettype($value))
                {
                    case 'NULL':
                        $fields[] = $column . ' = NULL';
                        break;

                    case 'array':
                        preg_match("/\(JSON\)\s*([\w]+)/i", $key, $column_match);

                        $fields[] = $column . ' = ' . $this->quote(
                                isset($column_match[0]) ? json_encode($value) : serialize($value)
                            );
                        break;

                    case 'boolean':
                        $fields[] = $column . ' = ' . ($value ? '1' : '0');
                        break;

                    case 'integer':
                    case 'double':
                    case 'string':
                        $fields[] = $column . ' = ' . $this->fn_quote($key, $value);
                        break;
                }
            }
        }

        return $this->exec('UPDATE "' . $table . '" SET ' . implode(', ', $fields) . $this->where_clause($where));
    }

    public function delete($table, $where)
    {
        return $this->exec('DELETE FROM "' . $table . '"' . $this->where_clause($where));
    }

    public function replace($table, $columns, $search = null, $replace = null, $where = null)
    {
        if (is_array($columns))
        {
            $replace_query = array();

            foreach ($columns as $column => $replacements)
            {
                foreach ($replacements as $replace_search => $replace_replacement)
                {
                    $replace_query[] = $column . ' = REPLACE(' . $this->column_quote($column) . ', ' . $this->quote($replace_search) . ', ' . $this->quote($replace_replacement) . ')';
                }
            }

            $replace_query = implode(', ', $replace_query);
            $where = $search;
        }
        else
        {
            if (is_array($search))
            {
                $replace_query = array();

                foreach ($search as $replace_search => $replace_replacement)
                {
                    $replace_query[] = $columns . ' = REPLACE(' . $this->column_quote($columns) . ', ' . $this->quote($replace_search) . ', ' . $this->quote($replace_replacement) . ')';
                }

                $replace_query = implode(', ', $replace_query);
                $where = $replace;
            }
            else
            {
                $replace_query = $columns . ' = REPLACE(' . $this->column_quote($columns) . ', ' . $this->quote($search) . ', ' . $this->quote($replace) . ')';
            }
        }

        return $this->exec('UPDATE "' . $table . '" SET ' . $replace_query . $this->where_clause($where));
    }

    public function get($table, $join = null, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where) . ' LIMIT 1');

        if ($query)
        {
            $data = $query->fetchAll(PDO::FETCH_ASSOC);

            if (isset($data[0]))
            {
                $column = $where == null ? $join : $column;

                if (is_string($column) && $column != '*')
                {
                    return $data[ 0 ][ $column ];
                }

                return $data[ 0 ];
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public function has($table, $join, $where = null)
    {
        $column = null;

        $query = $this->query('SELECT EXISTS(' . $this->select_context($table, $join, $column, $where, 1) . ')');

        return $query ? $query->fetchColumn() === '1' : false;
    }

    public function count($table, $join = null, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'COUNT'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function max($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'MAX'));

        if ($query)
        {
            $max = $query->fetchColumn();

            return is_numeric($max) ? $max + 0 : $max;
        }
        else
        {
            return false;
        }
    }

    public function min($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'MIN'));

        if ($query)
        {
            $min = $query->fetchColumn();

            return is_numeric($min) ? $min + 0 : $min;
        }
        else
        {
            return false;
        }
    }

    public function avg($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'AVG'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function sum($table, $join, $column = null, $where = null)
    {
        $query = $this->query($this->select_context($table, $join, $column, $where, 'SUM'));

        return $query ? 0 + $query->fetchColumn() : false;
    }

    public function debug()
    {
        $this->debug_mode = true;

        return $this;
    }

    public function error()
    {
        return $this->pdo->errorInfo();
    }

    public function last_query()
    {
        return end($this->logs);
    }

    public function log()
    {
        return $this->logs;
    }

    public function info()
    {
        $output = array(
            'server' => 'SERVER_INFO',
            'driver' => 'DRIVER_NAME',
            'client' => 'CLIENT_VERSION',
            'version' => 'SERVER_VERSION',
            'connection' => 'CONNECTION_STATUS'
        );

        foreach ($output as $key => $value)
        {
            $output[ $key ] = $this->pdo->getAttribute(constant('PDO::ATTR_' . $value));
        }

        return $output;
    }
}
?>
View Code

然后附上index.php文件,这个文件暂时只修改了table下的url,就是通过url="./data/crud/userAction.php?flag=list"来访问userAction地址,通过flag在userAction中区分跳转到userModel中去,找对应的方法实现。

index.php

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>dataGrid</title>
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="../ui/jquery-easyui-1.4.5/themes/color.css">
    <script src="../ui/jquery-easyui-1.4.5/jquery.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/jquery.easyui.min.js"></script>
    <script src="../ui/jquery-easyui-1.4.5/locale/easyui-lang-zh_CN.js"></script>
    <script src="../js/crud/bus_pubuser.js"></script>
</head>
<body>
    <table id="dg" title="用户列表" class="easyui-datagrid" style="width:550px;height:250px" url="./data/crud/userAction.php?flag=list" toolbar="#toolbar" rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="fname" width="50">名</th>
                <th field="lname" width="50">姓</th>
                <th field="sex" width="50">性别</th>
                <th field="phone" width="50">联系电话</th>
                <th field="email" width="50">邮件</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">修改</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteUser()">删除</a>
    </div>
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
        <div id="dlg" class="easyui-dialog" style="width:400px;height:320px;padding:10px 20px;" closed="true" buttons="#dlg-buttons">
        <div class="ftitle">基本信息</div>
        <hr />
        <form id="fm" method="post">
            <div class="fitem">
                <p>
                    <label>First Name:</label>
                    <input name="fname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Last Name:</label>
                    <input name="lname" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Sex:</label>
                    <input name="sex" class="easyui-validatebox" required="true">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Phone:</label>
                    <input name="phone">
                </p>
            </div>
            <div class="fitem">
                <p>
                    <label>Email:</label>
                    <input name="email" class="easyui-validatebox" validType="email">
                </p>
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>
    </div>
</body>
<html>
View Code

修改bus_pubuser.js的请求路径,同样也是通过flag在userAction中来标识,在userModel下找方法。

bus_pubuser.js

/*
 * crud   用户部分
 */
//添加用户
function newUser(){
    $('#dlg').dialog('open').dialog('setTitle','添加用户');
    $('#fm').form('clear');
    url = './data/crud/userAction.php?flag=add';
}
//修改用户
function editUser(){
    var row = $('#dg').datagrid('getSelected');
    if (row){
        $('#dlg').dialog('open').dialog('setTitle','修改用户');
        $('#fm').form('load',row);
        url = './data/crud/userAction.php?flag=modify&id='+row.id;
    }
}

//保存用户
function saveUser(){
    $('#fm').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(result){
            //alert(result);
            var result = eval('('+result+')');
            if (result.errorMsg){
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                $('#dlg').dialog('close');        // close the dialog
                $('#dg').datagrid('reload');    // reload the user data
            }
        }
    });
}
//删除用户
function deleteUser(){
    var row = $('#dg').datagrid('getSelected');
    var url = './data/crud/userAction.php?flag=delete';
    if(row){
            $.messager.confirm('Confirm','你确定要删除【'+row.lname+row.fname+'】么?',function(r){
            if (r){
                $.post(url,{id:row.id},function(result){
                    if (result.success){
                        $('#dg').datagrid('reload');    // reload the user data
                    } else {
                        $.messager.show({    // show error message
                            title: 'Error',
                            msg: result.errorMsg
                        });
                    }
                },'json');
            }
        });
    }
}
View Code

userAction.php

<?php 
    require_once "../../model/crud/userModel.php";
    $flag = $_GET["flag"];
    if(isset($_GET["id"])){
        $id=$_GET["id"];
    }else if(isset($_POST["id"])){
        $id=$_POST["id"];
    }else{
        $id="";
    }
    $user = new userModel();
    switch($flag){
        case "list" : $user->list_user();
            break;
        case "add" : $user->save_user($_POST);
            break;
        case "modify" : $user->edit_user($_POST,$id);
            break;
        case "delete" : $user->delete_user($id);
            break;
        default: $user->showErrorMsg();
    }
View Code

userModel.php

<?php 
    require_once "../../../common/medoo.php";
    header("Content-Type: text/html; charset=UTF-8");
    class userModel{
        function showErrorMsg(){
            echo json_encode(array('errorMsg'=>'没有相应的操作模块!'));
        }
        
        function list_user(){
            $medoo = new medoo();
            $result = $medoo->select("eui_user","*");
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
        }
        
        
        function save_user($arr){
            $medoo = new medoo();
            //var_dump($arr);
            //$arrayName = array($_POST);
            $result = $medoo->insert("eui_user",$arr);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        function edit_user($arr,$id){
            $medoo = new medoo();
            $result = $medoo->update("eui_user",$arr," where id=".$id);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        function delete_user($id){
            $medoo = new medoo();
            $result = $medoo->delete("eui_user"," where id=".$id);
            if($result){
                echo json_encode(array('success'=>true));
            }else{
                echo json_encode(array('errorMsg'=>'操作过程出现错误!'));
            }
        }
        
        
    }
View Code

以上这些都是代码优化,但是在这里面还有一个问题,就是页面操作合不合理,问题描述:在弹出添加按钮的时候,还是可以点击修改按钮,缺少遮罩层。

查看API文件可以知道,dialog继承window,在window下面一个属性角modal,将其设为true就可以了。

posted on 2016-07-10 01:40  EthanCoco  阅读(2590)  评论(0编辑  收藏  举报

导航