PHP – EasyUI DataGrid 资料存的方式介绍_php教程
继上篇文章 PHP – EasyUI DataGrid 资料取的方式,本篇继续讲述,如何操作 DataGrid,把资料存入资料库,并实现 MVC 架构,将资料层分离、独立运作。
本篇文章主要是改良,原 EasyUI DataGrid 的范例 Build CRUD Application with jQuery EasyUI。
在官方范例中已经示范如何操作资料,但其中有个问题就是,你要操作资料的每个动作都需要一支对应的程式才能动作,像是新增、删除、修改以及取得资料,总共至少要有四支对应程式才能运作。
读者可以想想,这还只是一支单档 使用者的基本资料维护而已,一般系统光基本资料都有十几支甚至几十支程式在运作,所以这样的方式,势必要改良才能运作在实务上。
在来按造 多层次架构设计前言 的精神,大家可以发现这四支程式其实对每一个基本资料的操作来说,都是大同小异的,所以是可以把他标准化,用成一个固定框架,供后面类似程式来使用。
这部分,会分几篇文章来逐渐完成这各过程,藉由这逐渐演进的过程,来了解框架是如何成形的。
首先本篇,先来介绍,如何把分散的四支程式集中成为一支程式来呼叫,在读者往下阅读之前,可先在了解 PHP – EasyUI DataGrid 资料取的方式 以及官方范例 Build CRUD Application with jQuery EasyUI 的运作方式,至少要能把范例 Run 起来,run 这个动作是很重要的,不要光看而已,亲身去测试才能了解其中的问题点。
要能实现将四支程式改成一支程式来运作,其实关键很简单,就是去改每个操作动作时呼叫的 url,改成都呼叫 DAL 端的程式 dal_user.php,接下来在呼叫前,都要传递一个 type 参数告诉 dal 你要进行何种动作。
目前 type 定义了下面四个动作
add 新增
mod 修改
del 删除
data 取得资料
了解 想要 dal 作哪些动作后,就可以开始来撰写 dal 程式了,当然现在这各 dal 还是一个非标准化的程式,但是他已经做到 MVC 的精神,把资料存取层跟表现层 分离开了,后面的文章, 会再来介绍,如何把本篇介绍的程式来标准化 dal 以及 UI 表现层。
dal_user.php
代码如下:
<?php $result = false; if (!empty($_REQUEST['type']) ) { require_once(".\..\db\DB_config.php"); require_once(".\..\db\DB_class.php"); $db = new DB(); $db->connect_db($_DB['host'], $_DB['username'], $_DB['password'], $_DB['dbname']); $tablename = "STUser"; $type = $_REQUEST['type']; if($type == "del") { $id = $_REQUEST['id']; $sql = "delete from STUser where UNum=$id"; $result = $db->query($sql); }else if($type == "data"){ $page = isset($_POST['page']) ? intval($_POST['page']) : 1; $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; $offset = ($page-1)*$rows; $result = array(); $db->query("select count(*) As Total from $tablename"); $row = $db->fetch_assoc(); $result["total"] = $row["Total"]; $db->query("select * from $tablename limit $offset,$rows"); $items = array(); while($row = $db->fetch_assoc()){ array_push($items, $row); } $result["rows"] = $items; echo json_encode($result); }else{ $STUID = $_REQUEST['STUID']; $Password = $_REQUEST['Password']; $Nickname = $_REQUEST['Nickname']; $Birthday = $_REQUEST['Birthday']; if (!empty($_REQUEST['id']) ) { $id = $_REQUEST['id']; $sql = "update $tablename set STUID='$STUID',Password='$Password',Nickname='$Nickname' where UNum=$id"; }else{ // is add $sql = "insert into $tablename (STUID, Password, Nickname, DBSTS) values('$STUID','$Password','$Nickname', 'A')"; } $result = $db->query($sql); } } if($type != "data") { if ($result == "true"){ echo json_encode(array('success'=>true)); } else { echo json_encode(array('msg'=>'had errors occured. ' . $result)); } } ?>
dal 资料存取层 定义完了以后,就可以来实现 UI 介面来呼叫 dal,因为是使用 AJAX 的方式 来存取资料,所以 MVC 中的控制层有一部分是放在 介面层中,这部分,后面可以在用 JavaScript 将这部分的控制层标准化,在藉由 php 后端来传递参数呼叫,如此一来,则还是将所有控制大权集中在一支程式中,这些后面文章会再来介绍,这边先暂时打住。
datagrid.php
代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>easyUI datagrid</title> <link rel="stylesheet" type="text/css" href="./../JS/EasyUI/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="./../JS/EasyUI/themes/icon.css"> <script type="text/javascript" src="./../JS/jquery.js"></script> <script type="text/javascript" src="./../JS/EasyUI/jquery.easyui.min.js"></script> <script type="text/javascript" src="./../JS/EasyUI/easyui-lang-zh_CN.js"></script> <style type="text/css"> #fm{ margin:0; padding:10px 30px; } .ftitle{ font-size:14px; font-weight:bold; color:#666; padding:5px 0; margin-bottom:10px; border-bottom:1px solid #ccc; } .fitem{ margin-bottom:5px; } .fitem label{ display:inline-block; width:80px; } </style> <script type="text/javascript"> var url; function newUser(){ $('#dlg').dialog('open').dialog('setTitle','New User'); $('#fm').form('clear'); url = 'dal_user.php?type=add'; } function editUser(){ var row = $('#myDG').datagrid('getSelected'); if (row){ if(typeof(row.UNum) !== 'undefined') { $('#dlg').dialog('open').dialog('setTitle','Edit User'); $('#fm').form('load',row); url = 'dal_user.php?type=mod&id='+row.UNum; }else{ alert("undefined"); } } } function saveUser(){ $('#fm').form('submit',{ url: url, onSubmit: function(){ //alert('sub :'+ url); return $(this).form('validate'); }, success: function(result){ var result = eval('('+result+')'); //alert(result.success); if (result.success){ $('#dlg').dialog('close'); // close the dialog $('#myDG').datagrid('reload'); // reload the user data } else { $.messager.show({ title: 'Error', msg: result.msg }); } } }); } function removeUser(){ var row = $('#myDG').datagrid('getSelected'); if (row){ $.messager.confirm('Confirm','Are you sure you want to remove this user?',function(r){ if (r){ //alert(row.UNum); $.post('dal_user.php', {type:'del', id:row.UNum}, function(result){ if (result.success){ $('#myDG').datagrid('reload'); // reload the user data } else { $.messager.show({ // show error message title: 'Error', msg: result.msg }); } },'json'); } }); } } </script> </head> <body> <h2>easyUI datagrid url 存取測試</h2> <table id="myDG" class="easyui-datagrid" style="width:700px;height:450px" url="dal_user.php?type=data" toolbar="#toolbar" title="Load Data" iconCls="icon-save" pagination="true" toolbar="#toolbar" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="STUID" width="120">User ID</th> <th field="Password" width="80" align="right">Password</th> <th field="Birthday" width="80" align="right">Birthday</th> <th field="Nickname" width="200">Nickname</th> <th field="DBSTS" width="60" align="center">DBSTS</th> </tr> </thead> </table> <p id="toolbar"> <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a> <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a> <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a> </p> <p id="dlg" class="easyui-dialog" style="width:400px;height:350px;padding:10px 20px" closed="true" buttons="#dlg-buttons"> <p class="ftitle">User Information</p> <form id="fm" method="post" novalidate> <p class="fitem"> <label>User ID:</label> <input name="STUID" class="easyui-validatebox" required="true"> </p> <p class="fitem"> <label>Password:</label> <input name="Password" class="easyui-validatebox" required="true"> </p> <p class="fitem"> <label>Nickname:</label> <input name="Nickname"> </p> <p class="fitem"> <label>Birthday:</label> <input name="Birthday" class="easyui-validatebox" validType="email"> </p> </form> </p> <p id="dlg-buttons"> <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a> <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a> </p> </body> </html>
运作结果画面如下所示:

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Alipay PHP ...

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> 'Hello World', 'github.com'=> [ 'foo'=> 'bar'], 'forge.laravel.com'=>

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

PHP 개발에서 PHP의 CURL 라이브러리를 사용하여 JSON 데이터를 보내면 종종 외부 API와 상호 작용해야합니다. 일반적인 방법 중 하나는 컬 라이브러리를 사용하여 게시물을 보내는 것입니다 ...
