As a PHP developer, we often need to operate the database. In actual projects, we often need to use pop-up windows to implement some operations, such as deletion, modification, etc.
This article will introduce how to operate the database through PHP pop-up windows, aiming to help readers better master this skill.
1. Preparation work
Before implementing the pop-up window, we need to prepare the following work:
1. Database connection: We need to use PHP to create a database connection.
2. Database query: We need to use PHP to query the database to obtain the data that needs to be operated.
3. Pop-up window code: We need to use JavaScript or jQuery to write the pop-up window code.
For the convenience of demonstration, here we use MySQL as the database and PHP PDO to connect to the database.
2. Delete data
Below we will introduce how to delete data through pop-up windows. First, we need to get the data to be deleted from the database and then display it on the page to facilitate user selection.
1. Query data
We can use the following code to query the data that needs to be deleted:
<?php //连接数据库 $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = '123456'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //异常处理模式 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //默认的查询结果类型 ]; $pdo = new PDO($dsn, $username, $password, $options); //查询要删除的数据 $sql = "SELECT * FROM test_table WHERE status = 0"; //status字段表示待删除数据 $stmt = $pdo->prepare($sql); $stmt->execute(); $data = $stmt->fetchAll(); ?>
In the above code, we first connect to the database and use the SELECT statement to query the data that needs to be deleted. The data. Among them, the status field indicates the data to be deleted.
- Display data
Next, we display the queried data on the page for users to select.
ID | Name | Action | |
---|---|---|---|
In the above code, we use HTML tables to display the queried data on the page. In order to implement the delete function, we add a delete button to each row of data and store its corresponding ID value through the data-id attribute.
- Delete data
Finally, let’s implement the delete function. When the user clicks the delete button, we will pop up a confirmation box asking the user whether to delete the data. If the user confirms the deletion, we will send an AJAX request to delete the data from the database.
$('.delete-btn').on('click', function() { var id = $(this).data('id'); if (confirm('确定要删除吗?')) { $.ajax({ url: 'delete.php', //处理删除请求的PHP文件 type: 'POST', data: {id: id}, success: function(res) { if (res.code === 0) { alert('删除成功'); window.location.reload(); //刷新页面 } else { alert('删除失败,请稍后再试'); } }, error: function() { alert('请求失败,请稍后再试'); } }); } });
In the above code, we use jQuery to bind the click event of the delete button. When the user clicks the delete button, we first get the ID value of the data, and use the confirm function to pop up a confirmation box asking the user if they want to delete it. If the user clicks to confirm, we will send a POST request to the delete.php file to delete the data from the database.
Note: The code in the delete.php file is as follows:
<?php //连接数据库 $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = '123456'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //异常处理模式 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //默认的查询结果类型 ]; $pdo = new PDO($dsn, $username, $password, $options); //删除数据 $id = $_POST['id']; $sql = "DELETE FROM test_table WHERE id = :id"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $res = $stmt->execute(); //返回结果 if ($res) { echo json_encode(['code' => 0, 'msg' => '删除成功']); } else { echo json_encode(['code' => 1, 'msg' => '删除失败']); } ?>
In the above code, we first connect to the database, and then use the DELETE statement to delete the data from the database. Finally, we return the results in JSON format.
3. Modify data
In addition to deleting data, we often need to modify data. Below, we will introduce how to modify data through pop-up windows.
- Query data
First, we need to query the data that needs to be modified from the database and display it on the page to facilitate users to modify it.
<?php //连接数据库 $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = '123456'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //异常处理模式 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //默认的查询结果类型 ]; $pdo = new PDO($dsn, $username, $password, $options); //查询要修改的数据 $id = $_GET['id']; $sql = "SELECT * FROM test_table WHERE id = :id"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->execute(); $data = $stmt->fetch(); ?>
In the above code, we first obtain the ID of the data that needs to be modified through $_GET['id']. Then, we use the SELECT statement to query the data from the database.
- Display data
Next, we display the queried data on the page to facilitate user modification. Here we still use the HTML form to fill the queried data into the form.
Note that we added a hidden field to the form to store the ID value of the data that needs to be modified.
- Modify data
Finally, let’s implement the modification function. When the user clicks the save button, we will send an AJAX request to update the modified data into the database.
$('.submit-btn').on('click', function() { var data = $('form').serialize(); $.ajax({ url: 'update.php', //处理修改请求的PHP文件 type: 'POST', data: data, success: function(res) { if (res.code === 0) { alert('修改成功'); window.location.href = 'index.php'; //跳转到列表页 } else { alert('修改失败,请稍后再试'); } }, error: function() { alert('请求失败,请稍后再试'); } }); });
In the above code, we use jQuery to bind the click event of the save button. When the user clicks the save button, we first get all the data in the form through the serialize function and send it to the update.php file. Here we use POST method to send data.
Note: The code in the update.php file is as follows:
<?php //连接数据库 $dsn = 'mysql:host=localhost;dbname=test;charset=utf8'; $username = 'root'; $password = '123456'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //异常处理模式 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //默认的查询结果类型 ]; $pdo = new PDO($dsn, $username, $password, $options); //修改数据 $id = $_POST['id']; $name = $_POST['name']; $email = $_POST['email']; $sql = "UPDATE test_table SET name = :name, email = :email WHERE id = :id"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':id', $id, PDO::PARAM_INT); $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->bindParam(':email', $email, PDO::PARAM_STR); $res = $stmt->execute(); //返回结果 if ($res) { echo json_encode(['code' => 0, 'msg' => '修改成功']); } else { echo json_encode(['code' => 1, 'msg' => '修改失败']); } ?>
In the above code, we first connect to the database, and then use the UPDATE statement to update the data into the database. Finally, we return the results in JSON format.
Note that for the convenience of demonstration, here we use the serialization function to convert the form data into a string, but in actual projects, we usually use the FormData object to process the form data to support functions such as uploading files.
4. Summary
Through the introduction of this article, we have learned how to operate the database through PHP pop-up windows. Whether it is deletion or modification, we can use similar methods to achieve it. I hope this article can provide some help to readers. If there is anything you still don’t understand, you can leave a message for discussion.
The above is the detailed content of How to operate the database through PHP pop-up windows. 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 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 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 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

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
