PHP interface and front-end data interaction implementation example code

coldplay.xixi
Release: 2023-04-09 09:02:02
forward
2677 people have browsed it

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[&#39;action&#39;];

  switch($action) {
    case &#39;init_data_list&#39;:
      init_data_list();
      break;
    case &#39;add_row&#39;:
      add_row();
      break;
    case &#39;del_row&#39;:
      del_row();
      break;
    case &#39;edit_row&#39;:
      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;
  }
?>
Copy after login

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 = $(&#39;#table&#39;),
        $remove = $(&#39;#remove&#39;);

      $(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: &#39;json&#39;,
          contentType: &#39;application/json; charset=utf-8&#39;,
          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) {
              $(&#39;#table&#39;).bootstrapTable(&#39;load&#39;, displayData);
            } else {
              console.log("last page or empty.");
            }
          },
          error: function(data) {
            alert(&#39;服务器出错&#39;);
          },
        });
      }

      $(&#39;#table&#39;).bootstrapTable({
        pagination: true,
        sidePagination: &#39;server&#39;, //设置为服务器端分页
        pageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 50, 100],
        search: true,
        showColumns: true,
        showRefresh: true,
        columns: [{
          field: &#39;state&#39;,
          checkbox: true,
        }, {
          field: &#39;user_id&#39;,
          title: &#39;用户Id&#39;,
          width: &#39;50&#39;,
          align: &#39;center&#39;,
          valign: &#39;middle&#39;
        }, {
          field: &#39;user_name&#39;,
          title: &#39;用户名称&#39;,
          width: &#39;500&#39;,
          align: &#39;center&#39;,
          valign: &#39;middle&#39;
        }, {
          field: &#39;user_age&#39;,
          title: &#39;用户年龄&#39;,
          width: &#39;500&#39;,
          align: &#39;center&#39;,
          valign: &#39;middle&#39;
        }, {
          field: &#39;user_sex&#39;,
          title: &#39;用户性别&#39;,
          width: &#39;500&#39;,
          align: &#39;center&#39;,
          valign: &#39;middle&#39;
        }, {
          field: &#39;user_add&#39;,
          title: &#39;编辑&#39;,
          formatter: forwardFormatter,
          width: &#39;500&#39;,
          align: &#39;center&#39;,
          valign: &#39;middle&#39;
        }]
      }).on(&#39;page-change.bs.table&#39;, function(e, page, size) {
        fillData();
      }).on(&#39;check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table&#39;, function() {
        var tes = !$table.bootstrapTable(&#39;getSelections&#39;).length
        $remove.prop(&#39;disabled&#39;, !$table.bootstrapTable(&#39;getSelections&#39;).length);
      });

      
      function forwardFormatter(value, row, index) {
        var value = "修改";
        return "<a href=&#39;#/" + row.user_id + "&#39; class=&#39;btn btn-link&#39;>" + value + "</a>";
      }
    </script>
  </body>
</html>
Copy after login

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[&#39;action&#39;];

  switch($action) {
    case &#39;init_data_list&#39;:
      init_data_list();
      break;
    case &#39;add_row&#39;:
      add_row();
      break;
    case &#39;del_row&#39;:
      del_row();
      break;
    case &#39;edit_row&#39;:
      edit_row();
      break;
  }

//删除方法
  function del_row(){
    //测试
    /*echo "ok!";*/
    
    //接收传回的参数
    $rowId = $_GET[&#39;rowId&#39;];
    $sql = "delete from t_users where user_id=&#39;$rowId&#39;";
    
    if(query_sql($sql)){
      echo "ok!";
    }else{
      echo "删除失败!";
    }
  }
?>
Copy after login

Front-end implementation JS part:

var $table = $(&#39;#table&#39;),
  $remove = $(&#39;#remove&#39;);

  $(function() {
    delData();
  });

function delData() {
        $remove.on(&#39;click&#39;, function() {
          if(confirm("是否继续删除")) {
            var rows = $.map($table.bootstrapTable(&#39;getSelections&#39;), function(row) {
              //返回选中的行的索引号
              return row.user_id;
            });
          }
          
          $.map($table.bootstrapTable(&#39;getSelections&#39;),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: &#39;application/json;charset=utf-8&#39;,
              success: function(data) {
                $table.bootstrapTable(&#39;remove&#39;,{
                  field: &#39;user_id&#39;,
                  values: rows
                });
                $remove.prop(&#39;disabled&#39;, true);
              },
              error:function(data){
                alert(&#39;删除失败!&#39;);
              }
            });
          });
        })
      }
Copy after login

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[&#39;action&#39;];

  switch($action) {
    case &#39;init_data_list&#39;:
      init_data_list();
      break;
    case &#39;add_row&#39;:
      add_row();
      break;
    case &#39;del_row&#39;:
      del_row();
      break;
    case &#39;edit_row&#39;:
      edit_row();
      break;
  }

//新增方法
  function add_row(){
    /*获取从客户端传过来的数据*/
    $userName = $_GET[&#39;user_name&#39;];
    $userAge = $_GET[&#39;user_age&#39;];
    $userSex = $_GET[&#39;user_sex&#39;];
    //INSERT INTO 表名 (列名1,列名2,...)VALUES (&#39;对应的数据1&#39;,&#39;对应的数据2&#39;,...)
    // VALUES 的值全为字符串,因为表属性设置为字符串
    $sql = "INSERT INTO t_users (user_name,user_age,user_sex) VALUES (&#39;$userName&#39;,&#39;$userAge&#39;,&#39;$userSex&#39;)";
    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;
  }
?>
Copy after login

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">&times;</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=&#39;-1&#39;>请选择</option>
                    <option value=&#39;0&#39;>男</option>
                    <option value=&#39;1&#39;>女</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>
Copy after login
var $table = $(&#39;#table&#39;),
   $remove = $(&#39;#remove&#39;);

  $(function() {
      searchData();
    delData();
        
    $(&#39;#save&#39;).click(function(){
      addData();
    });
  }); 
function addData(){
        var userName = $(&#39;#userName&#39;).val();
        var userAge = $("#userAge").val();
        var userSex = $(&#39;#user-sex&#39;).val() == &#39;0&#39; ? &#39;男&#39; : &#39;女&#39;;
        
        var addUrl = "./php/data.php?action=add_row&user_name=" + userName + "&user_age=" + userAge + "&user_sex=" + userSex;
        
        $.ajax({
          type:"post",
          url:addUrl,
          dataType:&#39;json&#39;,
          contentType:&#39;application/json;charset=utf-8&#39;,
          success:function(data){
            console.log("success");
          },
          error:function(data){
            console.log("data");
            //添加成功后隐蒧modal框
            setTimeout(function(){
              $(&#39;#exampleModal&#39;).modal(&#39;hide&#39;);
            },500);
              //隐藏modal框后重新加载当前页
            setTimeout(function(){
              searchData();
            },700);
          }
        });
      }
Copy after login
So far, nothing Solve the following problems:


1. Form verification;


2. After adding multiple pieces of data, how does php receive parameters;


3 After the addition is successful, in the $.ajax method, why should other operations after the addition be implemented in the error object? Instead of implementing it in sucess?

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!

Related labels:
source:jb51.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!