search
HomeBackend DevelopmentPHP TutorialPHP – EasyUI DataGrid data storage method introduction_php tutorial

Following the previous article PHP - EasyUI DataGrid data retrieval method, this article continues to describe how to operate DataGrid, store data in the database, and implement MVC architecture to separate the data layer and operate independently.

This article is mainly an improvement on the original EasyUI DataGrid example Build CRUD Application with jQuery EasyUI.

Official examples have demonstrated how to operate data, but one problem is that each action you want to take to operate data requires a corresponding program, such as adding, deleting, modifying, and To obtain data, a total of at least four corresponding programs are required to operate.

Readers can think about it, this is just the basic data maintenance of a single user. Generally, the system has more than a dozen or even dozens of programs operating just the basic data, so this method is bound to be It takes improvement to make it work in practice.
According to the spirit of the preface to multi-level architecture design, you can find that these four programs are actually similar to each basic data operation, so they can be standardized and used as a fixed framework. , for use by similar programs later.

This part will be divided into several articles to gradually complete each process. Through this gradual evolution process, we will understand how the framework is formed.
First of all, this article will introduce how to integrate four scattered programs into one program to call. Before reading further, readers can first understand the method of data retrieval in PHP - EasyUI DataGrid and the official example of Build CRUD The operation method of Application with jQuery EasyUI must at least be able to run the example. The run action is very important. Don't just look at it. Only by testing it yourself can you understand the problem points.

To be able to change four programs into one program to operate, the key is actually very simple, which is to change the url called during each operation to call the DAL program dal_user.php, then Before calling, you must pass a type parameter to tell dal what action you want to perform.
Currently type defines the following four actions:
add new
mod modify
del delete
data obtain data
After you understand what actions you want dal to do, you can start writing. dal program. Of course, this dal program is still a non-standard program, but it has achieved the spirit of MVC and separated the data access layer from the presentation layer. In the following articles, I will introduce how to introduce this article. Program to standardize dal and UI presentation layer.

dal_user.php

The code is as follows:

<?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 information After the access layer is defined, you can implement the UI interface to call DAL. Because AJAX is used to access data, part of the control layer in MVC is placed in the interface layer. This part can be used later. JavaScript standardizes this part of the control layer and uses the PHP backend to pass parameter calls. In this way, all control powers are concentrated in one program. These will be introduced in later articles, but we will stop here for now.

datagrid.php

The code is as follows:

<!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 id="easyUI-nbsp-datagrid-nbsp-url-nbsp-存取測試">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>


The operation result screen is as follows:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Discover File Downloads in Laravel with Storage::downloadDiscover File Downloads in Laravel with Storage::downloadMar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

How to Register and Use Laravel Service ProvidersHow to Register and Use Laravel Service ProvidersMar 07, 2025 am 01:18 AM

Laravel's service container and service providers are fundamental to its architecture. This article explores service containers, details service provider creation, registration, and demonstrates practical usage with examples. We'll begin with an ove

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version