The PHP interface interacts with the front-end data to implement sample code

Source: Internet
Author: User
Tags cloudflare
This article mainly introduces the PHP interface and the front-end data Interaction Implementation example code, mainly using Php+bootstrap-table+js, with a certain reference value, interested can understand

Recently in the attempt to do the front-end data interaction, but also jumped a lot of pits, using PHP+BOOTSTRAP-TABLE+JS, some of the harvest records here, easy to query.

This small project, there are only 3 files, respectively:

1.crud.html
2.data.php
3.crud.sql

Data interaction Implementation 1: Query

1.mysql Database Build Table
2.php Query Interface
3. Front-end data presentation

MySQL Database Build table

    • Database name: crud

    • First table name: T_users

    • Primary key: user_id, self-growing arrangement

Php:

<?php//Test whether PHP can get the data in the database/*echo "44444"; *//do a route action is a parameter in the 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    }//Query method function Init_data_list () {///test run crud.html can get to the following string/*echo "46545465465456465"; *//query table    $sql = "SELECT * from ' t_users '";    $query = Query_sql ($sql);    while ($row = $query->fetch_assoc ()) {$data [] = $row; } $json = Json_encode (Array ("ResultCode" =>200, "message" = "=" Query succeeded!)        "," data "= $data), json_unescaped_unicode);  Convert to String json echo ($json); /** Query the server for data * 1, connect to the database, the parameters are server address/username/password/database name * 2, return an array containing the parameter list * 3, traverse the $SQLS array, and assign the value returned to $s * 4, execute A MySQL query statement * 5, close the database * 6, return the data after execution * * 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 implementations:

<! DOCTYPE html>

Implementation results:

Data Interaction Implementation 2: Delete

In doing the deletion encountered a lot of pits, the reason is because the SQL statement is not familiar with PHP, but, summed up the following points for reference:

The parameters returned by 1.delete can only be obtained by $_get;

The parameters returned by 2.delete are placed in the URL, not in the body, and the parameters in the body are used for querying;

3.SQL statement must be skilled, one step wrong, step by step wrong;

4. To execute the SQL statement in the database to check if the statement is executed correctly, use the Rest Client to test the URL request correctly;

Php:

<?php  //test whether PHP can get the data in the database  /*echo "44444"; *    //Do a route action is a parameter in the 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;  } Delete method  function Del_row () {    //test    /*echo "ok!"; *        ///Receive back parameters    $rowId = $_get[' rowId ');    $sql = "Delete from t_users where user_id= ' $rowId '";        if (Query_sql ($sql)) {      echo "ok!";    } else{      echo "Delete failed! ";    }  }? >

The front-end Implementation JS section:

var $table = $ (' #table '), $remove = $ (' #remove ');  $ (function () {deldata (); }); function Deldata () {$remove. On (' click ', function () {if (Confirm ("continue delete)") {var rows = $.m            AP ($table. bootstraptable (' getselections '), function (row) {//returns the index number of the selected row return row.user_id;          }); } $.map ($table. bootstraptable (' getselections '), function (row) {var del_url = "./php/data.php"            ;                        Delete data according to UserID, because this ID is the parameter passed to the server var rowId = row.user_id; $.ajax ({type: "delete", Url:del_url + "? action=del_row&rowid=" + RowId, Datatyp                E: "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 (' Delete failed!              ');          }            });        }); })      }

Debugging method:

Data Interaction Implementation 3: New

In the way of writing PHP, I think my method is problematic, because all the parameters, that is, all the required new data are through the interface? followed by the way the argument was added successfully. function can be implemented, but if the new data is large, this method is not feasible, but has not found a suitable method, please the heroes.

Php:

<?php//Test whether PHP can get the data in the database/*echo "44444"; *//do a route action is a parameter in the 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    }//New Method function Add_row () {/* Gets data transmitted from the client/$userName = $_get[' user_name '];    $userAge = $_get[' user_age ');    $userSex = $_get[' user_sex '); INSERT into table name (column name 1, column Name 2, ...) VALUES (' corresponding data 1 ', ' corresponding data 2 ', ... Values are all strings, because the table property is set to string $sql = "INSERT into t_users (user_name,user_age,user_sex) VALUES (' $userName ', ' $user    Age ', ' $userSex ');    if (Query_sql ($sql)) {echo "ok!"; }else{echo "added success!    ";    }} 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; }?>

The front-end Implementation JS section:

HTML uses Bootstrap's modal as the new pop-up box

<!--new Bullet box--<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" & Gt;<span aria-hidden= "true" >x</span></button> 

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 '?                ' Male ': ' Female '; var addurl = "./php/data.php?action=add_row&user_name=" + userName + "&user_age=" + userage + "&user_sex=" + u                Sersex; $.ajax ({type: "Post", Url:addurl, DataType: ' JSON ', ContentType: ' Application/json;chars          Et=utf-8 ', success:function (data) {Console.log ("success");            }, Error:function (data) {Console.log ("data");            Add success after hidden forest modal box setTimeout (function () {$ (' #exampleModal '). Modal (' hide ');              },500);        Hides the modal box and reloads the current page setTimeout (function () {searchdata ();    },700);      }        }); }

At this point, the following questions have not been resolved:

1. Verification of forms;

2. After adding multiple data, how PHP receives the parameters;

3. After the new success, in the $.ajax method, why, the new success of the other operations to be implemented in the Error object? Instead of being implemented in sucess?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.