Home  >  Article  >  PHP Framework  >  How to delete by id in thinkphp

How to delete by id in thinkphp

PHPz
PHPzOriginal
2023-04-11 09:13:24578browse

ThinkPHP is an excellent PHP development framework, developed using the MVC model, providing a friendly development environment and rich development tools. When developing web applications, it is often necessary to add, delete, modify, and check operations, among which deletion operations are also indispensable. Let's learn how to delete data by id.

First, we need to create a controller, say called IndexController.

<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\User;

class IndexController extends Controller
{
    public function delete($id)
    {
        $result = User::where(&#39;id&#39;, $id)->delete();
        if ($result) {
            $this->success('删除成功', '');
        } else {
            $this->error('删除失败');
        }
    }
}

In the above code, we assume that we have a user data table. The data table is named "user" and there is a column called id to store the user's ID. We create a controller, create a delete method in the controller, and delete the user based on $id through the User model.

In the above code we call the static method delete() of the model. This method will delete records from the database based on specified conditions and return the number of deleted records. In our example, we use the where() method to specify the condition for deleting a user whose id is equal to the $id passed in.

Finally, we need to create a link in the view page to trigger this controller method.

<a href="{:url(&#39;index/delete&#39;, [&#39;id&#39;=>$user['id']])}">删除</a>

In the above code, we use the url() function provided by ThinkPHP to generate a url address by passing an array parameter, which contains the id parameter. The value of this parameter is $ user['id'], which is the ID of the corresponding user. When the user clicks the link, it will automatically jump to our delete method, which will delete the user based on the ID passed in.

To summarize, deleting data by id is very convenient in ThinkPHP. We only need to create a delete method in the controller, delete the data based on the id through the model's delete method, and then create a link in the view page to trigger this method.

The above is the detailed content of How to delete by id in thinkphp. 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