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.
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.
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.
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.
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.
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.