Preface
Tables are a commonly used way to display data on web pages, and sometimes we need to allow users to edit data through tables, so we need to use editable tables. As a server-side scripting language, php can operate on tables, and when used with ajax, it can update data asynchronously without reloading the entire web page. In this article, we will introduce how to implement editable tables using php and ajax.
Implementation steps
- Create database and data table
First, create a database named "editable_table" in the mysql database, and then create a A data table named "users" is used to store user information. The structure of the table is as follows:
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `phone` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- Create php file
Create a php file named "table.php" for reading user information from the database, And display it in table form on the web page. The code is as follows:
<?php // 连接数据库 $conn = mysqli_connect('localhost', 'root', 'password', 'editable_table'); if (!$conn) { die('连接数据库失败: ' . mysqli_connect_error()); } // 查询数据库,获取用户信息 $sql = "SELECT * FROM users"; $result = mysqli_query($conn, $sql); // 输出表格 echo "<table><thead><tr> <th>ID</th> <th>姓名</th> <th>邮箱</th> <th>电话</th> </tr></thead><tbody>"; while ($row = mysqli_fetch_assoc($result)) { echo "<tr> <td>" . $row['id'] . "</td> <td>" . $row['name'] . "</td> <td>" . $row['email'] . "</td> <td>" . $row['phone'] . "</td> </tr>"; } echo "</tbody>"; // 关闭数据库连接 mysqli_close($conn); ?>
- Add editable function
Now we can display user information on the web page, but we want users to be able to edit data through the form. In order to achieve this functionality, we need to add some javascript code.
First, we need to add a "contenteditable" attribute to turn the table cell into an editable state. In addition, we also need to add an event listener to send the modified data to the server when the content in the cell is modified.
The code is as follows:
nbsp;html> <meta> <title>可编辑表格</title> <div></div> <script></script> <script> // 读取数据表并将其展示在网页上 function loadTable() { $.ajax({ url: 'table.php', type: 'GET', success: function(result) { $('#table-container').html(result); } }); } // 点击单元格时,将它设为可编辑状态 $(document).on('click', 'td[contenteditable=false]', function() { $(this).attr('contenteditable', true); $(this).addClass('editable-cell'); $(this).focus(); }); // 当修改单元格中的内容时,将修改的数据发送到服务器端 $(document).on('blur', 'td[contenteditable=true]', function() { var row = $(this).parent(); var id = row.children().eq(0).text(); var name = row.children().eq(1).text(); var email = row.children().eq(2).text(); var phone = row.children().eq(3).text(); $.ajax({ url: 'update_table.php', type: 'POST', data: { id: id, name: name, email: email, phone: phone }, success: function(result) { loadTable(); } }); $(this).attr('contenteditable', false); $(this).removeClass('editable-cell'); }); // 加载数据表 $(document).ready(function() { loadTable(); }); </script> <style> .editable-cell { background-color: #fff2cc; } </style>
- Write a php file to update data
Finally, we need to write a php file named "update_table.php" , used to update new data into the database. The code is as follows:
<?php // 连接数据库 $conn = mysqli_connect('localhost', 'root', 'password', 'editable_table'); if (!$conn) { die('连接数据库失败: ' . mysqli_connect_error()); } // 获取POST请求中的参数 $id = $_POST['id']; $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; // 更新数据库中的数据 $sql = "UPDATE users SET name='$name', email='$email', phone='$phone' WHERE id='$id'"; $result = mysqli_query($conn, $sql); // 输出结果 if ($result) { echo "修改成功"; } else { echo "修改失败"; } // 关闭数据库连接 mysqli_close($conn); ?>
At this point, we have completed all the steps to implement editable tables with php and ajax. When we refresh the web page, we can realize the related functions of editable tables.
Summary
In this article, we introduced how to use php and ajax to implement editable tables. By using the "contenteditable" attribute and event listeners, we can make table cells editable and upload the modified data to the server for updates via ajax. In this way, users can easily edit and save data through the web page.
The above is the detailed content of How to implement editable tables with php and ajax. For more information, please follow other related articles on the PHP Chinese website!

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
