


PHP interface and front-end data interaction implementation example code
Recently I have been trying to interact with front-end and back-end data, and I have jumped into a lot of pitfalls. I use php bootstrap-table js and record some gains here for easy query.
This small project has only 3 files, namely:
1.crud.html
2.data.php
3.crud.sql
Related learning recommendations: PHP programming from entry to proficiency
Data interaction implementation 1: Query
1.mysql database table creation
2.php query interface
3.Front-end data display
mysql database table creation
- Database name: crud
- First table name: t_users
- Primary key: user_id, self-increasing arrangement
php:
<?php //测试php是否可以拿到数据库中的数据 /*echo "44444";*/ //做个路由 action为url中的参数 $action = $_GET['action']; switch($action) { case 'init_data_list': init_data_list(); break; case 'add_row': add_row(); break; case 'del_row': del_row(); break; case 'edit_row': edit_row(); break; } //查询方法 function init_data_list(){ //测试 运行crud.html时是否可以获取到 下面这个字符串 /*echo "46545465465456465";*/ //查询表 $sql = "SELECT * FROM `t_users`"; $query = query_sql($sql); while($row = $query->fetch_assoc()){ $data[] = $row; } $json = json_encode(array( "resultCode"=>200, "message"=>"查询成功!", "data"=>$data ),JSON_UNESCAPED_UNICODE); //转换成字符串JSON echo($json); } /**查询服务器中的数据 * 1、连接数据库,参数分别为 服务器地址 / 用户名 / 密码 / 数据库名称 * 2、返回一个包含参数列表的数组 * 3、遍历$sqls这个数组,并把返回的值赋值给 $s * 4、执行一条mysql的查询语句 * 5、关闭数据库 * 6、返回执行后的数据 */ function query_sql(){ $mysqli = new mysqli("127.0.0.1", "root", "root", "crud"); $sqls = func_get_args(); foreach($sqls as $s){ $query = $mysqli->query($s); } $mysqli->close(); return $query; } ?>
Front-end implementation:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="external nofollow" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="external nofollow" > <!-- jQuery --> <script type="text/javascript" src="http://code.changer.hk/jquery/1.11.2/jquery.min.js"></script> <script type="text/javascript" src="http://code.changer.hk/jquery/plugins/jquery.cookie.js"></script> <!-- bootstrap-table --> <link rel="stylesheet" href="http://code.changer.hk/bootstrap-table/1.6.0/bootstrap-table.min.css" rel="external nofollow" > <script type="text/javascript" src="http://code.changer.hk/bootstrap-table/1.6.0/bootstrap-table.min.js"></script> <style type="text/css"> #table { padding: 0; } #table>tbody>tr { cursor: pointer; } #table>tbody>tr>td.bs-checkbox { vertical-align: middle; } </style> <title>增删改查</title> </head> <body style="padding: 50px;"> <p class="toolbar1" style="margin-bottom: -43px;"> <button id="remove" class="btn btn-danger" disabled>删除</button> <button class="btn btn-primary" id="btn">新建</button> </p> <p id="table"></p> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.min.js"></script> <!-- Latest compiled and minified Locales --> <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script> <script type="text/javascript"> var $table = $('#table'), $remove = $('#remove'); $(function() { searchData(); }); function prepareDisplayData(data) { return { total: data.data.length, fixedScroll: false, rows: data.data }; } function searchData() { var search_url = "./php/data.php"; //url 中问号后面的参数 action,这个对象就是查询的参数 var dataParam = { action: "init_data_list" }; $.ajax({ type: "get", url: search_url, data: dataParam, dataType: 'json', contentType: 'application/json; charset=utf-8', success: function(data) { //测试是否可以拿到php中的数据 console.log(data); //遍历这个数组 if(data.resultCode == 200) { var itemArr = data.data; for(var i = 0; i < itemArr.length; i++) { var item = itemArr[i]; console.log(item); } } //bootstrap-table 组织数据 var displayData = prepareDisplayData(data); if(displayData.total > 0) { $('#table').bootstrapTable('load', displayData); } else { console.log("last page or empty."); } }, error: function(data) { alert('服务器出错'); }, }); } $('#table').bootstrapTable({ pagination: true, sidePagination: 'server', //设置为服务器端分页 pageNumber: 1, pageSize: 10, pageList: [10, 20, 50, 100], search: true, showColumns: true, showRefresh: true, columns: [{ field: 'state', checkbox: true, }, { field: 'user_id', title: '用户Id', width: '50', align: 'center', valign: 'middle' }, { field: 'user_name', title: '用户名称', width: '500', align: 'center', valign: 'middle' }, { field: 'user_age', title: '用户年龄', width: '500', align: 'center', valign: 'middle' }, { field: 'user_sex', title: '用户性别', width: '500', align: 'center', valign: 'middle' }, { field: 'user_add', title: '编辑', formatter: forwardFormatter, width: '500', align: 'center', valign: 'middle' }] }).on('page-change.bs.table', function(e, page, size) { fillData(); }).on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', function() { var tes = !$table.bootstrapTable('getSelections').length $remove.prop('disabled', !$table.bootstrapTable('getSelections').length); }); function forwardFormatter(value, row, index) { var value = "修改"; return "<a href='#/" + row.user_id + "' class='btn btn-link'>" + value + "</a>"; } </script> </body> </html>
Implementation effect:
##Data interaction implementation 2: Delete
I encountered a lot of pitfalls when deleting. The reason is that I am not familiar with SQL statements and PHP. However, I have summarized the following points for reference: 1.delete returned Parameters can only be obtained using $_GET; 2.delete The returned parameters must be placed in the URL, not in the body; the parameters in the body are used for query; 3. You must be proficient in SQL statements. One wrong step will lead to a wrong step; 4. To execute the SQL statement in the database to check whether the statement is executed correctly, you must use Rest Client to test whether the URL request is correct; php:<?php //测试php是否可以拿到数据库中的数据 /*echo "44444";*/ //做个路由 action为url中的参数 $action = $_GET['action']; switch($action) { case 'init_data_list': init_data_list(); break; case 'add_row': add_row(); break; case 'del_row': del_row(); break; case 'edit_row': edit_row(); break; } //删除方法 function del_row(){ //测试 /*echo "ok!";*/ //接收传回的参数 $rowId = $_GET['rowId']; $sql = "delete from t_users where user_id='$rowId'"; if(query_sql($sql)){ echo "ok!"; }else{ echo "删除失败!"; } } ?>
var $table = $('#table'), $remove = $('#remove'); $(function() { delData(); }); function delData() { $remove.on('click', function() { if(confirm("是否继续删除")) { var rows = $.map($table.bootstrapTable('getSelections'), function(row) { //返回选中的行的索引号 return row.user_id; }); } $.map($table.bootstrapTable('getSelections'),function(row){ var del_url = "./php/data.php"; //根据userId删除数据,因为这个id就是 传给服务器的参数 var rowId = row.user_id; $.ajax({ type:"delete", url:del_url + "?action=del_row&rowId=" + rowId, dataType:"html", contentType: 'application/json;charset=utf-8', success: function(data) { $table.bootstrapTable('remove',{ field: 'user_id', values: rows }); $remove.prop('disabled', true); }, error:function(data){ alert('删除失败!'); } }); }); }) }
Data interaction implementation 3: New addition
In terms of the method of writing PHP, I think there is a problem with my method, because all the parameters, that is, All the data that needs to be added is through the interface? The method followed by parameters is added successfully. The function can be implemented, but if the newly added data is large, this method is not feasible, but a suitable method has not been found yet. Please give me some advice. php:<?php //测试php是否可以拿到数据库中的数据 /*echo "44444";*/ //做个路由 action为url中的参数 $action = $_GET['action']; switch($action) { case 'init_data_list': init_data_list(); break; case 'add_row': add_row(); break; case 'del_row': del_row(); break; case 'edit_row': edit_row(); break; } //新增方法 function add_row(){ /*获取从客户端传过来的数据*/ $userName = $_GET['user_name']; $userAge = $_GET['user_age']; $userSex = $_GET['user_sex']; //INSERT INTO 表名 (列名1,列名2,...)VALUES ('对应的数据1','对应的数据2',...) // VALUES 的值全为字符串,因为表属性设置为字符串 $sql = "INSERT INTO t_users (user_name,user_age,user_sex) VALUES ('$userName','$userAge','$userSex')"; if(query_sql($sql)){ echo "ok!"; }else{ echo "新增成功!"; } } function query_sql(){ $mysqli = new mysqli("127.0.0.1", "root", "root", "crud"); $sqls = func_get_args(); foreach($sqls as $s){ $query = $mysqli->query($s); } $mysqli->close(); return $query; } ?>
<!--新增弹框--> <p class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"> <p class="modal-dialog" role="document"> <p class="modal-content"> <p class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="exampleModalLabel">用户新增</h4> </p> <p class="modal-body"> <form id="listForm" method="post"> <p class="form-group"> <label for="userName" class="control-label">用户名称</label> <input type="text" class="form-control" id="userName"> </p> <p class="form-group"> <label for="userAge" class="control-label">用户年龄</label> <input type="text" class="form-control" id="userAge"> </p> <p class="form-group"> <label class="control-label" for="user-sex">用户性别</label> <p class=""> <select id="user-sex" class="form-control" name="user-sex" style="width: 100%" > <option value='-1'>请选择</option> <option value='0'>男</option> <option value='1'>女</option> </select> </p> </p> </form> </p> <p class="modal-footer"> <button id="close" type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button id="save" type="button" class="btn btn-primary">保存</button> </p> </p> </p> </p>
var $table = $('#table'), $remove = $('#remove'); $(function() { searchData(); delData(); $('#save').click(function(){ addData(); }); }); function addData(){ var userName = $('#userName').val(); var userAge = $("#userAge").val(); var userSex = $('#user-sex').val() == '0' ? '男' : '女'; var addUrl = "./php/data.php?action=add_row&user_name=" + userName + "&user_age=" + userAge + "&user_sex=" + userSex; $.ajax({ type:"post", url:addUrl, dataType:'json', contentType:'application/json;charset=utf-8', success:function(data){ console.log("success"); }, error:function(data){ console.log("data"); //添加成功后隐蒧modal框 setTimeout(function(){ $('#exampleModal').modal('hide'); },500); //隐藏modal框后重新加载当前页 setTimeout(function(){ searchData(); },700); } }); }
The above is the detailed content of PHP interface and front-end data interaction implementation example code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
