


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 "删除失败!"; } } ?>Front-end implementation JS part:
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('删除失败!'); } }); }); }) }Debugging method:
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; } ?>Front-end implementation JS part: html uses bootstrap’s modal as a pop-up box when adding new items
<!--新增弹框--> <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 id="用户新增">用户新增</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); } }); }So far, nothing Solve the following problems:
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.