In recent years, with the rapid development and popularization of Web technology, more and more websites and applications have adopted AJAX technology to achieve a more dynamic and intelligent interactive experience. In WEB programming, PHP is a very commonly used server-side programming language. Therefore, combining PHP and AJAX technology to implement addition, deletion, modification and query operations has become the first choice of many WEB developers. This article will introduce how to use PHP and AJAX technology to implement the add, delete, modify and check functions.
Before introducing PHP and AJAX technology, we need to understand some basic syntax and data manipulation methods of PHP:
1.1 PHP basic syntax
PHP is a dynamic, interpreted server-side scripting language. Its basic syntax format includes:
1. PHP code starts with End.
2. The PHP statement ends with a semicolon “;”.
3. PHP variables start with the $ symbol, such as $name.
4. There are two ways to comment in PHP: // for single-line comments, and /.../ for multi-line comments.
The following is an example of PHP syntax:
<?php // 这是单行注释 /* 这是多行注释 */ $name = "Tom"; // 定义一个变量 echo "Hello, ".$name."!"; // 输出变量 ?>
1.2 PHP data operation
PHP can interact with a variety of databases, such as MySQL, Oracle, SQL Server, etc. In PHP, the MySQL database is mainly used, and the interaction with the MySQL database is achieved through extension libraries such as MySQLi or PDO. The following are the basic operations of PHP and MySQL database:
1. Connect to the database
$con = mysqli_connect("localhost","username","password","dbname");
2. Execute SQL statements and return the result set
$sql = "SELECT * FROM Users"; $result = mysqli_query($con,$sql);
3. Read the results in the result set Data
while($row = mysqli_fetch_array($result)) { echo $row['UserName']; echo $row['Password']; echo $row['Email']; }
4. Close the database connection
mysqli_close($con);
In this article, we will take the user management system as an example , introduces how to use AJAX and PHP to implement the following four functions:
1. Query user information
2. Add new users
3. Modify user information
4. Delete user information
2.1 Query user information
We first implement the function of querying user information, which contains two parts: the front-end page and the back-end PHP script.
2.1.1 Front-end page
We use HTML and AJAX to implement the front-end page for querying user information:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>用户管理系统 - 查询</title> </head> <body> <h1>用户管理系统 - 查询</h1> <table border="1" cellpadding="10"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>密码</th> <th>邮箱</th> </tr> </thead> <tbody id="user_table"> </tbody> </table> <script> $(document).ready(function(){ $.ajax({ url:'query_user.php', type:'get', dataType:'json', success:function(data){ if(data.code==0){ var users = data.data; var tr = ''; for(var i=0;i<users.length;i++){ tr += '<tr>' +'<td>'+users[i].id+'</td>' +'<td>'+users[i].username+'</td>' +'<td>'+users[i].password+'</td>' +'<td>'+users[i].email+'</td>' +'</tr>'; } $('#user_table').append(tr); } }, error:function(){ alert('查询失败!'); } }); }); </script> </body> </html>
In the above code, we use the jQuery library to initiate an AJAX request , access the query_user.php script, and render the returned JSON format data into the page.
2.1.2 Back-end PHP script
The following is the code of query_user.php script:
<?php $con = mysqli_connect("localhost","username","password","dbname"); $sql = "SELECT * FROM users"; $result = mysqli_query($con,$sql); $users = array(); if(mysqli_num_rows($result)>0){ while($row = mysqli_fetch_assoc($result)){ $users[] = $row; } $response = array( 'code'=>0, 'message'=>'查询成功', 'data'=>$users ); }else{ $response = array( 'code'=>-1, 'message'=>'查询失败' ); } echo json_encode($response); mysqli_close($con); ?>
In the code, we return the query results in JSON format. If the query is successful, Then the value of the code field is 0, and the data field is the query result array; otherwise, the code field is -1, and the message field is the prompt information for query failure.
2.2 Add new user
When implementing the add new user function, we need to send user data to the PHP script, so we use the POST method, while JavaScript and PHP pass$_POST
Super global variables for parameter passing.
2.2.1 Front-end page
The following is the front-end page for adding new users:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>用户管理系统 - 添加</title> </head> <body> <h1>用户管理系统 - 添加</h1> <form id="add_form"> <label>用户名:</label> <input type="text" name="username"><br> <label>密码:</label> <input type="password" name="password"><br> <label>邮箱:</label> <input type="email" name="email"><br> <input type="submit" value="添加"> </form> <script> $(function(){ $('#add_form').submit(function(event){ event.preventDefault(); var data = $(this).serialize(); $.ajax({ url:'add_user.php', type:'post', dataType:'json', data:data, success:function(data){ if(data.code==0){ alert('添加成功!'); }else{ alert('添加失败!'); } }, error:function(){ alert('添加失败!'); } }); }); }); </script> </body> </html>
In the above code, we define a form and set each input box in the form name and type, and a button is reserved for submitting the form. In the button click event, we used jQuery's serialize()
method to encapsulate the form data into a string and submit it to the PHP script.
2.2.2 Back-end PHP script
The following is the code of the add_user.php script:
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $con = mysqli_connect("localhost","username","password","dbname"); $sql = "INSERT INTO users (username,password,email) VALUES ('$username','$password','$email')"; if(mysqli_query($con,$sql)){ $response = array( 'code'=>0, 'message'=>'添加成功' ); }else{ $response = array( 'code'=>-1, 'message'=>'添加失败' ); } echo json_encode($response); mysqli_close($con); } ?>
In the code, we use $_POST
to obtain The form data passed by the front-end page is inserted into the MySQL database using the mysqli extension library.
2.3 Modify user information
When implementing the function of modifying user information, we need to query user information based on user ID and display the queried information on the front-end page. Users can modify the information Submit the form and save it.
2.3.1 Front-end page
The following is the front-end page for modifying user information:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>用户管理系统 - 修改</title> </head> <body> <h1>用户管理系统 - 修改</h1> <form id="edit_form"> <input type="hidden" name="id" value=""> <label>用户名:</label> <input type="text" name="username" value=""><br> <label>密码:</label> <input type="password" name="password" value=""><br> <label>邮箱:</label> <input type="email" name="email" value=""><br> <input type="submit" value="保存"> </form> <script> function queryUser(id){ $.ajax({ url:'query_user.php', type:'get', dataType:'json', data:{id:id}, success:function(data){ if(data.code==0){ var user = data.data[0]; $('input[name="id"]').val(user.id); $('input[name="username"]').val(user.username); $('input[name="password"]').val(user.password); $('input[name="email"]').val(user.email); }else{ alert('查询失败!'); } }, error:function(){ alert('查询失败!'); } }); } $(function(){ var id = parseInt(location.search.substring(4)); if(isNaN(id)){ alert('用户ID错误!'); }else{ queryUser(id); $('#edit_form').submit(function(event){ event.preventDefault(); var data = $(this).serialize(); $.ajax({ url:'edit_user.php', type:'post', dataType:'json', data:data, success:function(data){ if(data.code==0){ alert('保存成功!'); }else{ alert('保存失败!'); } }, error:function(){ alert('保存失败!'); } }); }); } }); </script> </body> </html>
In the above code, we define a hidden field in the form to store users ID, obtain the user ID value through query parameters, send an AJAX request to obtain user information, and display the information in the form. In the form submission event, we submit the user's modified information to the PHP script for update through the AJAX method.
2.3.2 Back-end PHP script
The following is the code of the edit_user.php script:
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ $id = $_POST['id']; $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; $con = mysqli_connect("localhost","username","password","dbname"); $sql = "UPDATE users SET username='$username',password='$password',email='$email' WHERE id=$id"; if(mysqli_query($con,$sql)){ $response = array( 'code'=>0, 'message'=>'保存成功' ); }else{ $response = array( 'code'=>-1, 'message'=>'保存失败' ); } echo json_encode($response); mysqli_close($con); } ?>
In the code, we still use $_POST
to obtain The form data passed by the front-end page and the user data in the database are updated using the mysqli extension library.
2.4 Delete user information
When implementing the function of deleting user information, we need to delete user information based on the user ID.
2.4.1 Front-end page
The following is the front-end page for deleting user information:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <title>用户管理系统 - 删除</title> </head> <body> <h1>用户管理系统 - 删除</h1> <table border="1" cellpadding="10"> <thead> <tr> <th>ID</th> <th>用户名</th> <th>密码</th> <th>邮箱</th> <th>操作</th> </tr> </thead> <tbody id="user_table"> </tbody> </table> <script> $(function(){ $.ajax({ url:'query_user.php', type:'get', dataType:'json', success:function(data){ if(data.code==0){ var users = data.data; var tr = ''; for(var i=0;i<users.length;i++){ tr += '<tr>' +'<td>'+users[i].id+'</td>' +'<td>'+users[i].username+'</td>' +'<td>'+users[i].password+'</td>' +'<td>'+users[i].email+'</td>' +'<td><a href="javascript:void(0);" onclick="deleteUser('+users[i].id+');">删除</a></td>' +'</tr>'; } $('#user_table').append(tr); } }, error:function(){ alert('查询失败!'); } }); }); function deleteUser(id){ if(confirm('确定要删除该用户吗?')){ $.ajax({ url:'delete_user.php', type:'post', dataType:'json', data:{id:id}, success:function(data){ if(data.code==0){ alert('删除成功!'); location.reload(); }else{ alert('删除失败!'); } }, error:function(){ alert('删除失败!'); } }); } } </script> </body> </html>
In the above code, we use AJAX to request all user information in the database and render it to the table. A "Delete" button is added to each row of the table. When clicked, an AJAX request is sent to delete the user information in the current row.
2.4.2 Back-end PHP script
The following is the code of delete_user.php script:
<?php if($_SERVER['REQUEST_METHOD']=='POST'){ $id = $_POST['id']; $con = mysqli_connect("localhost","username","password","dbname"); $sql = "DELETE FROM users WHERE id=$id"; if(mysqli_query($con,$sql)){ $response = array( 'code'=>0, 'message'=>'删除成功' ); }else{ $response = array( 'code'=>-1, 'message'=>'删除失败' ); } echo json_encode($response); mysqli_close($con); } ?>
In the code, we obtain the front-end through $_POST
The user ID passed by the page, and the corresponding user data is deleted from the database using the mysqli extension library.
This article introduces how to use PHP and AJAX technology to implement the add, delete, modify, and query functions. It elaborates on the implementation in terms of basic PHP syntax, MySQL data operations, and AJAX request sending. process, and provides supporting front-end pages and back-end PHP scripts. Learning and mastering the knowledge in this article can help developers complete WEB-based application development more efficiently.
The above is the detailed content of How to use PHP and AJAX technology to implement addition, deletion, modification and search functions. For more information, please follow other related articles on the PHP Chinese website!