php教程 php手册 PHP – EasyUI DataGrid 데이터 저장 방법 소개_php 기본

PHP – EasyUI DataGrid 데이터 저장 방법 소개_php 기본

May 16, 2016 am 09:00 AM
easyui

이전 기사인 PHP - EasyUI DataGrid 데이터 검색 방법에 이어 이번 기사에서는 DataGrid를 작동하는 방법, 데이터베이스에 데이터를 저장하는 방법, MVC 아키텍처를 구현하여 데이터 계층을 분리하고 독립적으로 작동하는 방법을 계속 설명합니다.

이 기사는 주로 원래 EasyUI DataGrid 예제 Build CRUD Application with jQuery EasyUI를 개선한 것입니다.

공식 사례에서는 데이터를 조작하는 방법을 보여 주었지만, 한 가지 문제는 데이터를 조작하기 위해 수행하려는 각 작업에 추가, 삭제, 수정, 데이터를 얻으려면 총 작동하려면 최소한 4개의 해당 프로그램이 필요합니다.

생각해보면 이는 한 명의 사용자에 대한 기본적인 데이터 관리일 뿐입니다. 일반적으로 시스템에는 기본 데이터만 운영하는 프로그램이 수십 개, 심지어 수십 개가 있기 때문에 이 방법을 사용하게 됩니다. 실제로 작동하려면 개선이 필요합니다.
다단계 아키텍처 설계 서문의 정신에 따르면, 이 네 가지 프로그램은 실제로 각 기본 데이터 작업과 유사하므로 표준화하여 유사한 프레임워크로 사용할 수 있음을 알 수 있습니다. 나중에 프로그램.

이 부분은 여러 개의 글로 나누어 각 과정을 점진적으로 완성해 나가면서 이러한 점진적인 진화 과정을 통해 프레임워크가 어떻게 형성되는지 알아보겠습니다.
먼저 이 글에서는 4개의 분산된 프로그램을 하나의 프로그램으로 통합하여 호출하는 방법을 소개합니다. 더 읽기 전에 독자는 먼저 PHP의 데이터 검색 방법인 EasyUI DataGrid와 Build CRUD의 공식 예제를 이해할 수 있습니다. jQuery EasyUI를 사용하는 애플리케이션 메서드는 최소한 예제를 실행할 수 있어야 합니다. 실행 작업을 지켜보는 것만으로는 문제를 이해할 수 없습니다.

4개의 프로그램을 하나의 프로그램으로 바꿔서 동작시키려면 사실 핵심은 매우 간단합니다. 각 동작 시 호출되는 url을 변경하여 DAL 프로그램 dal_user.php를 호출한 후 호출하기 전에, 수행하려는 작업을 dal에게 알리려면 유형 매개변수를 전달해야 합니다.
현재 유형은 다음 네 가지 작업을 정의합니다.
새 항목 추가
mod 수정
del 삭제
데이터 데이터 가져오기
dal이 수행하려는 작업을 이해한 후 쓰기를 시작할 수 있습니다. 물론 이 dal 프로그램은 아직은 비표준 프로그램이지만 MVC의 정신을 구현하고 프레젠테이션 계층에서 데이터 액세스 계층을 분리한 방법을 소개하겠습니다. .Dal 및 UI 프리젠테이션 레이어를 표준화하는 프로그램입니다.

dal_user.php

코드는 다음과 같습니다.

<?php 
$result = false; 
if (!empty($_REQUEST[&#39;type&#39;]) ) 
{ 
require_once(".\..\db\DB_config.php"); 
require_once(".\..\db\DB_class.php"); 
$db = new DB(); 
$db->connect_db($_DB[&#39;host&#39;], $_DB[&#39;username&#39;], $_DB[&#39;password&#39;], $_DB[&#39;dbname&#39;]); 
$tablename = "STUser"; 
$type = $_REQUEST[&#39;type&#39;]; 
if($type == "del") 
{ 
$id = $_REQUEST[&#39;id&#39;]; 
$sql = "delete from STUser where UNum=$id"; 
$result = $db->query($sql); 
}else if($type == "data"){ 
$page = isset($_POST[&#39;page&#39;]) ? intval($_POST[&#39;page&#39;]) : 1; 
$rows = isset($_POST[&#39;rows&#39;]) ? intval($_POST[&#39;rows&#39;]) : 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[&#39;STUID&#39;]; 
$Password = $_REQUEST[&#39;Password&#39;]; 
$Nickname = $_REQUEST[&#39;Nickname&#39;]; 
$Birthday = $_REQUEST[&#39;Birthday&#39;]; 
if (!empty($_REQUEST[&#39;id&#39;]) ) { 
$id = $_REQUEST[&#39;id&#39;]; 
$sql = "update $tablename set STUID=&#39;$STUID&#39;,Password=&#39;$Password&#39;,Nickname=&#39;$Nickname&#39; where UNum=$id"; 
}else{ // is add 
$sql = "insert into $tablename (STUID, Password, Nickname, DBSTS) values(&#39;$STUID&#39;,&#39;$Password&#39;,&#39;$Nickname&#39;, &#39;A&#39;)"; 
} 
$result = $db->query($sql); 
} 
} 
if($type != "data") 
{ 
if ($result == "true"){ 
echo json_encode(array(&#39;success&#39;=>true)); 
} else { 
echo json_encode(array(&#39;msg&#39;=>&#39;had errors occured. &#39; . $result)); 
} 
} 
?>
로그인 후 복사


dal 데이터 액세스 계층이 정의된 후 dal을 호출하는 UI 인터페이스를 구현하려면 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(){ 
$(&#39;#dlg&#39;).dialog(&#39;open&#39;).dialog(&#39;setTitle&#39;,&#39;New User&#39;); 
$(&#39;#fm&#39;).form(&#39;clear&#39;); 
url = &#39;dal_user.php?type=add&#39;; 
} 
function editUser(){ 
var row = $(&#39;#myDG&#39;).datagrid(&#39;getSelected&#39;); 
if (row){ 
if(typeof(row.UNum) !== &#39;undefined&#39;) 
{ 
$(&#39;#dlg&#39;).dialog(&#39;open&#39;).dialog(&#39;setTitle&#39;,&#39;Edit User&#39;); 
$(&#39;#fm&#39;).form(&#39;load&#39;,row); 
url = &#39;dal_user.php?type=mod&id=&#39;+row.UNum; 
}else{ 
alert("undefined"); 
} 
} 
} 
function saveUser(){ 
$(&#39;#fm&#39;).form(&#39;submit&#39;,{ 
url: url, 
onSubmit: function(){ 
//alert(&#39;sub :&#39;+ url); 
return $(this).form(&#39;validate&#39;); 
}, 
success: function(result){ 
var result = eval(&#39;(&#39;+result+&#39;)&#39;); 
//alert(result.success); 
if (result.success){ 
$(&#39;#dlg&#39;).dialog(&#39;close&#39;); // close the dialog 
$(&#39;#myDG&#39;).datagrid(&#39;reload&#39;); // reload the user data 
} else { 
$.messager.show({ 
title: &#39;Error&#39;, 
msg: result.msg 
}); 
} 
} 
}); 
} 
function removeUser(){ 
var row = $(&#39;#myDG&#39;).datagrid(&#39;getSelected&#39;); 
if (row){ 
$.messager.confirm(&#39;Confirm&#39;,&#39;Are you sure you want to remove this user?&#39;,function(r){ 
if (r){ 
//alert(row.UNum); 
$.post(&#39;dal_user.php&#39;, {type:&#39;del&#39;, id:row.UNum}, function(result){ 
if (result.success){ 
$(&#39;#myDG&#39;).datagrid(&#39;reload&#39;); // reload the user data 
} else { 
$.messager.show({ // show error message 
title: &#39;Error&#39;, 
msg: result.msg 
}); 
} 
},&#39;json&#39;); 
} 
}); 
} 
} 
</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:$(&#39;#dlg&#39;).dialog(&#39;close&#39;)">Cancel</a> 
</p> 
</body> 
</html>
로그인 후 복사


작업 결과 화면은 다음과 같습니다.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

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

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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