thinkphp6 is a very excellent PHP development framework. It is based on the MVC architecture. It has high development efficiency, is easy to use, is safe and reliable, and greatly simplifies the code writing process. Today, let’s talk about how to use thinkphp6 to implement multi-select deletion.
1. Introduction
Multi-select deletion is one of the common functions of modern web applications. It allows the user to select multiple items in a data table or list and then delete them. In this article, we will introduce how to use thinkphp6's controllers and models to achieve this functionality.
2. Create a database
First, we need to create a sample table in the MySQL database. We will use command line tools or phpMyAdmin to complete this step.
CREATE TABLE example_table
(
id
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(255) NOT NULL ,
email
varchar(255) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
This will create a new table called "example_table" with id, name and email fields.
3. Generate model and controller
Next, we need to generate a model and a controller based on the table structure created above.
Use thinkphp6's Artisan command line tool to quickly generate these files:
php think make:model ExampleModel --migration
Running the above command will generate a new model file ( app /Model/ExampleModel.php ) and a new database migration file ( database /migrations /yyyymmddhhmmss_create_example_model.php ).
php think make:controller ExampleController
Running the above command will generate a new file named ExampleController.php ( app /Controller/ExampleController.php ).
4. Write the code
Now we are ready to write the controller code to handle multi-select deletion. In the controller, we need to implement two main action functions: index (used to display all data) and delete (used to handle delete requests).
In the app/Controller/ExampleController.php file, add the following code:
<?php namespace appcontroller; use thinkacadeView; use thinkRequest; use appmodelExampleModel; class ExampleController { public function index() { $list = ExampleModel::all(); return View::fetch('index', [ 'list' => $list, ]); } public function delete(Request $request) { $ids = $request->param('ids'); foreach ($ids as $id) { ExampleModel::destroy($id); } return ['status' => 'success', 'message' => '删除成功']; } }
In the above code, we first imported the class and defined two functions index and delete. The function index is used to get all the data from the ExampleModel and pass it into the template. The function delete gets the list of IDs to be deleted from the HTTP request and deletes the items using the ExampleModel::destroy method.
Next, we need to add a multi-select box and delete button to the template. Open the app /View /example /index.html file and add the following code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> <h1 id="Example">Example</h1> <table> <thead> <tr> <th><input type="checkbox" id="check-all"></th> <th>ID</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> <?php foreach ($list as $item): ?> <tr> <td><input type="checkbox" name="ids[]" value="<?php echo $item->id ?>"></td> <td><?php echo $item->id ?></td> <td><?php echo $item->name ?></td> <td><?php echo $item->email ?></td> </tr> <?php endforeach ?> </tbody> </table> <button id="btn-delete">删除</button> <script> var btnDelete = document.querySelector('#btn-delete'); btnDelete.addEventListener('click', function () { var ids = []; var checkboxes = document.querySelectorAll('input[type=checkbox][name^=ids]:checked'); for (var i = 0; i < checkboxes.length; i++) { ids.push(checkboxes[i].value); } if (ids.length > 0) { if (confirm('确定删除?')) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/example/delete'); xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xhr.onload = function () { var result = JSON.parse(xhr.responseText); if (result.status == 'success') { alert(result.message); location.reload(); } else { console.error(result); alert('删除失败'); } }; xhr.onerror = function () { console.error(xhr); alert('网络异常,请重试'); }; xhr.send(JSON.stringify({ids: ids})); } } else { alert('请选择要删除的项目'); } }); var checkAll = document.querySelector('#check-all'); checkAll.addEventListener('click', function () { var checkboxes = document.querySelectorAll('input[type=checkbox][name^=ids]'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].checked = checkAll.checked; } }); </script> </body> </html>
In the above code, we used JavaScript to get all selected multi-select boxes and pass these IDs to the server's / delete route.
5. Test
Now, we can open the console and use the following command to start the web server.
php think run
Then enter localhost:8000/example in the browser to open the homepage of example, click the multi-select box to select the item to be deleted. Finally, click the Delete button to delete the selected item.
6. Conclusion
In this article, we use the controller, model and view of thinkphp6 to implement the multi-select deletion function. This feature can play an important role in web applications and optimize the user experience of the application.
The above is the detailed content of thinkphp multi-select delete. For more information, please follow other related articles on the PHP Chinese website!

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope


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

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.

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

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