基本增删改查(php)

此例子展示基于Datatables的服务器处理的增删改查,弹窗效果,结合Bootstrap显示表格,局部刷新数据,还应用了sdom,自定义按钮 使表格和按钮看起来是一个整体

注意:这个全选反选操作只针对当前页有效,不能跨页选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
var oTable;
$(document).ready(function () {
initModal();
oTable = initTable();
$("#btnEdit").hide();
$("#btnSave").click(_addFun);
$("#btnEdit").click(_editFunAjax);
$("#deleteFun").click(_deleteList);
//checkbox全选
$("#checkAll").live("click", function () {
    if ($(this).attr("checked") === "checked") {
        $("input[name='checkList']").attr("checked", $(this).attr("checked"));
    } else {
        $("input[name='checkList']").attr("checked", false);
    }
});
});
 
/**
* 表格初始化
* @returns {*|jQuery}
*/
function initTable() {
var table = $("#example").dataTable({
    //"iDisplayLength":10,
    'bPaginate': true,
    "bDestory": true,
    "bRetrieve": true,
    "bFilter":false,
    "bSort": false,
    "bProcessing": true,
    "aoColumns": [
        {
            "mDataProp": "id",
            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<input type='checkbox' name='checkList' value='" + sData + "'>");
 
            }
        },
        {"mDataProp": "name"},
        {"mDataProp": "job"},
        {"mDataProp": "date"},
        {"mDataProp": "note"},
        {
            "mDataProp": "id",
            "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='javascript:void(0);' " +
                "onclick='_editFun(\"" + oData.id + "\",\"" + oData.name + "\",\"" + oData.job + "\",\"" + oData.note + "\")'>编辑</a>&nbsp;&nbsp;")
                    .append("<a href='javascript:void(0);' onclick='_deleteFun(" + sData + ")'>删除</a>");
            }
        },
    ],
    "sDom": "<'row-fluid'<'span6 myBtnBox'><'span6'f>r>t<'row-fluid'<'span6'i><'span6 'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
        "sUrl": "../resources/user_share/basic_curd/jsplugin/datatables/zh-CN.txt",
        "sSearch": "快速过滤:"
    },
    "fnCreatedRow": function (nRow, aData, iDataIndex) {
        //add selected class
        $(nRow).click(function () {
            if ($(this).hasClass('row_selected')) {
                $(this).removeClass('row_selected');
            } else {
                oTable.$('tr.row_selected').removeClass('row_selected');
                $(this).addClass('row_selected');
            }
        });
    },
    "fnInitComplete": function (oSettings, json) {
        $('<a href="#myModal" id="addFun" class="btn btn-primary" data-toggle="modal">新增</a>' + '&nbsp;' +
        '<a href="#" class="btn btn-primary" id="editFun">修改</a> ' + '&nbsp;' +
        '<a href="#" class="btn btn-danger" id="deleteFun">删除</a>' + '&nbsp;').appendTo($('.myBtnBox'));
        $("#deleteFun").click(_deleteList);
        $("#editFun").click(_value);
        $("#addFun").click(_init);
    }
});
return table;
}
 
/**
* 删除
* @param id
* @private
*/
function _deleteFun(id) {
$.ajax({
    data: {"id": id},
    type: "post",
    success: function (backdata) {
        if (backdata) {
            oTable.fnReloadAjax(oTable.fnSettings());
        } else {
            alert("删除失败");
        }
    }, error: function (error) {
        console.log(error);
    }
});
}
 
/**
* 赋值
* @private
*/
function _value() {
if (oTable.$('tr.row_selected').get(0)) {
    $("#btnEdit").show();
    var selected = oTable.fnGetData(oTable.$('tr.row_selected').get(0));
    $("#inputName").val(selected.name);
    $("#inputJob").val(selected.job);
    $("#inputDate").val(selected.date);
    $("#inputNote").val(selected.note);
    $("#objectId").val(selected.id);
 
    $("#myModal").modal("show");
    $("#btnSave").hide();
} else {
    alert('请点击选择一条记录后操作。');
}
}
 
/**
* 编辑数据带出值
* @param id
* @param name
* @param job
* @param note
* @private
*/
function _editFun(id, name, job, note) {
$("#inputName").val(name);
$("#inputJob").val(job);
$("#inputNote").val(note);
$("#objectId").val(id);
$("#myModal").modal("show");
$("#btnSave").hide();
$("#btnEdit").show();
}
 
/**
* 初始化
* @private
*/
function _init() {
resetFrom();
$("#btnEdit").hide();
$("#btnSave").show();
}
 
/**
* 添加数据
* @private
*/
function _addFun() {
var jsonData = {
    'name': $("#inputName").val(),
    'job': $("#inputJob").val(),
    'note': $("#inputNote").val()
};
$.ajax({
    data: jsonData,
    type: "post",
    success: function (backdata) {
        if (backdata == 1) {
            $("#myModal").modal("hide");
            resetFrom();
            oTable.fnReloadAjax(oTable.fnSettings());
        } else if (backdata == 0) {
            alert("插入失败");
        } else {
            alert("防止数据不断增长,会影响速度,请先删掉一些数据再做测试");
        }
    }, error: function (error) {
        console.log(error);
    }
});
}
 
 
/*
add this plug in
// you can call the below function to reload the table with current state
Datatables刷新方法
oTable.fnReloadAjax(oTable.fnSettings());
*/
$.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings) {
//oSettings.sAjaxSource = sNewSource;
this.fnClearTable(this);
this.oApi._fnProcessingDisplay(oSettings, true);
var that = this;
 
$.getJSON(oSettings.sAjaxSource, null, function (json) {
    /* Got the data - add it to the table */
    for (var i = 0; i < json.aaData.length; i++) {
        that.oApi._fnAddData(oSettings, json.aaData[i]);
    }
    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    that.fnDraw(that);
    that.oApi._fnProcessingDisplay(oSettings, false);
});
}
 
 
/**
* 编辑数据
* @private
*/
function _editFunAjax() {
var id = $("#objectId").val();
var name = $("#inputName").val();
var job = $("#inputJob").val();
var note = $("#inputNote").val();
var jsonData = {
    "id": id,
    "name": name,
    "job": job,
    "note": note
};
$.ajax({
    type: 'POST',
    data: jsonData,
    success: function (json) {
        if (json) {
            $("#myModal").modal("hide");
            resetFrom();
            oTable.fnReloadAjax(oTable.fnSettings());
        } else {
            alert("更新失败");
        }
    }
});
}
/**
* 初始化弹出层
*/
function initModal() {
$('#myModal').on('show', function () {
    $('body', document).addClass('modal-open');
    $('<div class="modal-backdrop fade in"></div>').appendTo($('body', document));
});
$('#myModal').on('hide', function () {
    $('body', document).removeClass('modal-open');
    $('div.modal-backdrop').remove();
});
}
 
/**
* 重置表单
*/
function resetFrom() {
$('form').each(function (index) {
    $('form')[index].reset();
});
}
 
 
/**
* 批量删除
* 未做
* @private
*/
function _deleteList() {
var str = '';
$("input[name='checkList']:checked").each(function (i, o) {
    str += $(this).val();
    str += ",";
});
if (str.length > 0) {
    var IDS = str.substr(0, str.length - 1);
    alert("你要删除的数据集id为" + IDS);
} else {
    alert("至少选择一条记录操作");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered table-hover"
   id="example">
<thead>
<tr>
    <th style="width:15px"><input type="checkbox" id='checkAll'></th>
    <th>昵称</th>
    <th>技能</th>
    <th>添加时间</th>
    <th>备注</th>
    <th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
 
            <!-- Modal -->
<div id="myModal" class="modal hide fade" data-backdrop="false">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"
                aria-hidden="true"
        </button>
        <h3 id="myModalLabel">用户信息</h3>
    </div>
    <div class="modal-body">
        <form class="form-horizontal" id="resForm">
            <input type="hidden" id="objectId"/>
 
            <div class="control-group">
                <label class="control-label" for="inputName">昵称:</label> <input
                    type="text" id="inputName" name="name"/>
            </div>
            <div class="control-group">
                <label class="control-label" for="inputJob">技能:</label> <input
                    type="text" id="inputJob" name="job"/>
            </div>
            <div class="control-group">
                <label class="control-label" for="inputNote">备注:</label>
                <textarea name="note" id="inputNote" cols="30" rows="4"></textarea>
            </div>
        </form>
    </div>
    <div class="modal-footer">
        <button class="btn btn-primary" id="btnSave">确定</button>
        <button class="btn btn-primary" id="btnEdit">保存</button>
        <button class="btn btn-danger" data-dismiss="modal"
                aria-hidden="true">取消
        </button>
    </div>
</div>
F12查看
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
$output = array(
  "aaData" => array()
);
 
try {
    //连接数据库
    $db = new SQLite3('curd.sqlite3');
} catch (Exception $e) {
    fatal(
        "数据库连接出错" . $e->getMessage()
    );
}
$sql = "select * from user";
$result = $db->query($sql);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$row = array(
    "id" => $row['id'],
    "name" => $row['name'],
    "job" => $row['job'],
    "date" => $row['start_date'],
    "note" => $row['note']
 
);
$output['aaData'][] = $row;
}
$db->close();
echo json_encode( $output );
 
function fatal($msg)
{
echo json_encode(array(
    "error" => $msg
));
exit(0);
}
 
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$id = $_POST['id'];
try {
    //连接数据库
    $db = new SQLite3('curd.sqlite3');
} catch (Exception $e) {
    fatal(
        "数据库连接出错" . $e->getMessage()
    );
}
 
$query = "delete from user where id = " . $id;
$resultQ = $db->query($query);
if ($resultQ) {
    echo 1;
} else {
    echo 0;
}
$db->close();
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$job = $_POST['job'];
$note = $_POST['note'];
try {
//连接数据库
$db = new SQLite3('curd.sqlite3');
} catch (Exception $e) {
fatal(
    "数据库连接出错" . $e->getMessage()
);
}
$updateSql = "update user set name = '" . $name . "' , job = '" . $job . "', note = '" . $note . "' where id = " . $id;
$resultQ = $db->query($updateSql);
if ($resultQ) {
echo 1;
} else {
echo 0;
}
$db->close();
 
function fatal($msg)
{
echo json_encode(array(
    "error" => $msg
));
exit(0);
}
 
?>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
$name = $_POST['name'];
$job = $_POST['job'];
$note = $_POST['note'];
try {
    //连接数据库
    $db = new SQLite3('curd.sqlite3');
} catch (Exception $e) {
    fatal(
        "数据库连接出错" . $e->getMessage()
    );
}
$querySum = "select count(id) as sum from user";
$sumResult = $db->query($querySum);
$SUM=0;
while($row = $sumResult->fetchArray(SQLITE3_ASSOC)){
    $SUM = $row['sum'];
}
if($SUM<341341){
    $insertSql = "insert into user (name,job,note) " .
        "values('" . $name . "','" . $job . "','" . $note . "')";
    $result = $db->query($insertSql);
    $db->close();
    if ($result) {
        echo 1;
    } else {
        echo 0;
    }
}else{
    echo 2;
}
 
function fatal($msg)
{
    echo json_encode(array(
        "error" => $msg
    ));
    exit(0);
}
?>