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
What are the best practices for deduplication of PHP arraysWhat are the best practices for deduplication of PHP arraysMar 03, 2025 pm 04:41 PM

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

Can PHP array deduplication take advantage of key name uniqueness?Can PHP array deduplication take advantage of key name uniqueness?Mar 03, 2025 pm 04:51 PM

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

Does PHP array deduplication need to be considered for performance losses?Does PHP array deduplication need to be considered for performance losses?Mar 03, 2025 pm 04:47 PM

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

How to Implement message queues (RabbitMQ, Redis) in PHP?How to Implement message queues (RabbitMQ, Redis) in PHP?Mar 10, 2025 pm 06:15 PM

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

What Are the Latest PHP Coding Standards and Best Practices?What Are the Latest PHP Coding Standards and Best Practices?Mar 10, 2025 pm 06:16 PM

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

What are the optimization techniques for deduplication of PHP arraysWhat are the optimization techniques for deduplication of PHP arraysMar 03, 2025 pm 04:50 PM

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

How Do I Work with PHP Extensions and PECL?How Do I Work with PHP Extensions and PECL?Mar 10, 2025 pm 06:12 PM

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,

How to Use Reflection to Analyze and Manipulate PHP Code?How to Use Reflection to Analyze and Manipulate PHP Code?Mar 10, 2025 pm 06:12 PM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor