Current Location: Home> Latest Articles> Practical Guide to Deleting Multiple Records in ThinkPHP

Practical Guide to Deleting Multiple Records in ThinkPHP

gitbox 2025-08-08

Basic Principle of Deleting Multiple Records in ThinkPHP

ThinkPHP is a widely-used PHP development framework that comes with many built-in features to significantly improve development efficiency. This article focuses on how to use ThinkPHP to delete multiple records from a database in batch.

Approach to Deleting Multiple Records

The core of deleting multiple records is executing multiple delete operations, usually by looping through each record ID and executing a delete statement for each.

Preparing the Array of Record IDs to Delete

First, you need to prepare an array to store the IDs of records that need to be deleted. Example code is as follows:


$ids = array(1, 2, 3, 4);

The numbers represent the IDs of the records to be deleted.

Constructing the Delete Statement

An example SQL statement to delete a single record (deleting a record with ID 1 from the article table) is:


DELETE FROM `article` WHERE `id` = 1;

Here, article is the table name, id is the field, and 1 is the ID of the record to delete.

Executing Delete Operations in a Loop

Using a foreach loop to iterate over the array of IDs and execute each delete operation allows batch deletion. Example code:


foreach ($ids as $id) {
    $sql = "DELETE FROM `article` WHERE `id` = " . $id;
    $result = $model->execute($sql);
    if ($result === false) {
        // Error occurred, perform rollback
        $model->rollback();
        return false;
    }
}

Here, $model is the model object, and execute runs the SQL command. On success, it returns the number of affected rows; on failure, it returns false.

Summary

Following these steps, you can efficiently delete multiple records using the ThinkPHP framework. In real projects, the deletion logic can be customized to meet different business needs for more flexible and safe batch deletion.