search
HomeBackend DevelopmentPHP ProblemHow to implement editable tables with php and ajax

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

  1. 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;
  1. 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(&#39;localhost&#39;, &#39;root&#39;, &#39;password&#39;, &#39;editable_table&#39;);
  if (!$conn) {
    die(&#39;连接数据库失败: &#39; . 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);
?>
  1. 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: &#39;table.php&#39;,
        type: &#39;GET&#39;,
        success: function(result) {
          $(&#39;#table-container&#39;).html(result);
        }
      });
    }

    // 点击单元格时,将它设为可编辑状态
    $(document).on(&#39;click&#39;, &#39;td[contenteditable=false]&#39;, function() {
      $(this).attr(&#39;contenteditable&#39;, true);
      $(this).addClass(&#39;editable-cell&#39;);
      $(this).focus();
    });

    // 当修改单元格中的内容时,将修改的数据发送到服务器端
    $(document).on(&#39;blur&#39;, &#39;td[contenteditable=true]&#39;, 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: &#39;update_table.php&#39;,
        type: &#39;POST&#39;,
        data: { id: id, name: name, email: email, phone: phone },
        success: function(result) {
          loadTable();
        }
      });

      $(this).attr(&#39;contenteditable&#39;, false);
      $(this).removeClass(&#39;editable-cell&#39;);
    });

    // 加载数据表
    $(document).ready(function() {
      loadTable();
    });
  </script>
  <style>
    .editable-cell {
      background-color: #fff2cc;
    }
  </style>

  1. 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(&#39;localhost&#39;, &#39;root&#39;, &#39;password&#39;, &#39;editable_table&#39;);
  if (!$conn) {
    die(&#39;连接数据库失败: &#39; . mysqli_connect_error());
  }

  // 获取POST请求中的参数
  $id = $_POST[&#39;id&#39;];
  $name = $_POST[&#39;name&#39;];
  $email = $_POST[&#39;email&#39;];
  $phone = $_POST[&#39;phone&#39;];

  // 更新数据库中的数据
  $sql = "UPDATE users SET name=&#39;$name&#39;, email=&#39;$email&#39;, phone=&#39;$phone&#39; WHERE id=&#39;$id&#39;";
  $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!

Statement
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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.