1. Add a record
To add a new record in ThinkPHP, you need to use a model and a controller. First, you need to define the table name and field information in the model. For example, after defining the table name and field information in the model, you can add a record to the student table
class StudentModel extends Model { protected $tableName = 'student'; //表名 protected $fields = array('id', 'name', 'age', 'sex'); //字段信息 }
Then, create a Student object in the controller and specify the data to be added:
public function add() { $student = D('Student'); //实例化Student对象 $data = array( 'name' => 'Tom', 'age' => 18, 'sex' => '男' ); //要添加的数据 $student->add($data); //添加数据 }
2. Delete records
To delete a record in ThinkPHP, you need to use a model and a controller. In the controller, create an object named Student, and then delete the corresponding record by specifying the ID to be deleted
public function delete() { $id = 1; //要删除的记录的ID $student = D('Student'); //实例化Student对象 $student->delete($id); //执行删除操作 }
ThinkPHP's delete method will automatically delete data based on the primary key. If it needs to be deleted based on other conditions record, you can pass in an array as the second parameter in the delete method, for example:
public function delete() { $condition = array('age' => array('gt', 18)); //删除满足条件的记录(年龄大于18岁的记录) $student = D('Student'); //实例化Student对象 $student->where($condition)->delete(); //执行删除操作 }
3. Modify the record
Modify a record in ThinkPHP, Models and controllers are also required. First, create an object named Student, and then perform modification operations in the controller according to the ID of the record to be modified
public function update() { $id = 1; //要修改的记录的ID $student = D('Student'); //实例化Student对象 $data = array( 'name' => 'Jerry', 'age' => 20, 'sex' => '男' ); //要修改的数据 $student->where(array('id' => $id))->save($data); //执行修改操作 }
In the save method, you can choose whether to use the first parameter to specify the record to be modified. Recording conditions. If not specified, it will be modified based on the primary key.
The above is the detailed content of How to perform addition, deletion and modification operations under the ThinkPHP framework. For more information, please follow other related articles on the PHP Chinese website!