In the previous article, we learned about the basics of ThinkPHP, how to create a controller and template, and how to use the M method. This article will explain the CURD operation of data and explore more data operations.
CURD
CURD is an abbreviation in database technology. The basic functions of various parameters in general project development are CURD. It represents Create, Update, Read and Delete operations. CURD defines basic atomic operations for processing data. The reason why CURD is elevated to the level of a technical difficulty is that the performance of completing an aggregation-related activity involving CURD operations in multiple database systems may vary greatly as the data relationships change.
CURD does not necessarily use the create, update, read and delete methods in specific applications, but the functions they complete are the same. For example, ThinkPHP uses the add, save, select, and delete methods to represent the CURD operations of the model.
Create data
In most cases, CURD's Create operation usually submits data through a form. First, we create an add.html template file under the Tpl/Form directory of the project, with the content:
Then, we also need to create a FormAction.class.php file under the Action directory of the project. For the time being, we only need to define the FormAction class and do not need to add any operation methods. The code is as follows:
class FormAction extends Action{
}
Next, visit
http://localhost/app/index.php/Form/add
and you can see the form page. We have not defined the add operation method in the controller, but obviously the access is normal. of. Because ThinkPHP will check whether the corresponding template file exists if it does not find the corresponding operation method. Since we have the corresponding add template file, the controller directly renders the template file and outputs it. So for operation methods without any actual logic, we only need to directly define the corresponding template file.
We can see that the submission address defined in the form is the insert operation to the Form module. In order to process the form submission data, we need to add the insert operation method in the FormAction class, as follows:
class FormAction extends Action{
public function insert(){
function insert() $Form
if($ result) { $this->success('Operation successful!'); }$this->error($Form->getError()); If it is not an auto-incrementing primary key, the return value indicates the number of inserted data. If false is returned, it indicates a writing error.
Model
In order to facilitate testing, we first create a think_form table in the database:
CREATE TABLE IF NOT EXISTS `think_form` (
`id` smallint(4) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` varchar(255) NOT NULL,
`create_time` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE= MyISAM DEFAULT CHARSET=utf8 ;
We used the D function in the insert operation method. Unlike the M function, the D function needs a corresponding model class. Let’s create the model class below. The definition specification of the model class is: model name + Model.class.php (the model name is defined in camel case and the first letter is capitalized)
We create the FormModel.class.php file under the Lib/Model directory of the project and add the following code:
class FormModel extends Model {
// Define automatic validation
protected $_validate = array(
array('title','require','title must'),
);
// Define automatic Complete
protected $_auto = array(
array('create_time','time',1,'function'),
));
}
is mainly used for automatic verification and automatic completion of forms, specifically We will use another space to describe the usage separately, so we will skip it here for now. What we only need to understand is that if you use the D function to instantiate a model class, it generally needs to correspond to a data model class, and the create method will automatically verify and automatically complete the data submitted by the form (if defined). If the automatic verification fails , you can get the verification prompt information through the model's getError method. If the verification passes, it means that the data object has been successfully created, but it is currently only saved in memory until we call the add method to write the data to the database. This completes a complete Create operation, so you can see that ThinkPHP uses two steps in the process of creating data:
The first step, the create method creates the data object,
The second step, uses the add method to add the current data object Write to database.
Of course, you can skip the first step and go directly to the second step, but this kind of preprocessing has several advantages:
1. No matter how complex the form is, the create method can easily create a data object with one line of code;
2. Before writing data, the data can be verified and supplemented;
In fact, the create method also has many functional operations, with only one purpose, to ensure that the data written to the database is safe and effective.
Let’s verify the effect of form submission. When we submit the form directly without entering a title, the system will give a prompt that the title must be like this.
When we successfully submit the form, we will see that the create_time field in the data written to the data table already has a value, which is written through the automatic completion of the model.
If your data is completely written by internal operations rather than through the form (that is to say, the security of the data can be fully trusted), then you can use the add method directly, such as:
$Form = D('Form ');
$data['title'] = 'ThinkPHP';
$data['content'] = 'Form content';
$Form->add($data);
can also be supported Object mode operation:
$Form = D('Form');
$Form->title = 'ThinkPHP';
$Form->content = 'Form content';
$Form-> add();
When operating in object mode, the add method does not need to pass in data and will automatically identify the current data object assignment.
Read data
After we successfully write the data, we can perform the data reading operation. In the previous article, we already know that we can use the select method to obtain a data set. Here we will obtain a single data through the find method. The read operation method is defined as follows:
public function read($id=0){
$Form = M('Form');
//Read data
$data = $Form->find($id);
if($data) {
$this->data = $data ;// Template variable assignment
}
$this->display();
}
The read operation method has a parameter $id, which means that we can accept the id variable in the URL (we will describe it in detail in the variable chapter later. The reason why it is used here The reason why the M method is not used in the D method is because the find method is a method in the basic model class Model, so there is no need to waste overhead to instantiate the FormModel class (even if the FormModel class has been defined). We usually use the find method to read certain data. , AR mode is used here to operate, so no query conditions are passed in. find($id) means reading data whose primary key is the $id value. The return value of the find method is an array in the following format:
array(
'id' => 5,
'title' => 'Test title',
'content' => 'Test content',
'status' => 1,
)
Then We can output data in the template and add a read template file,
After completion, we can visit
http://localhost/app/index.php/Form/read/id/1
to view
If you only need to query a certain item. For the value of the field, you can also use the getField method, for example: $Form = M("Form"); // Get the title $title = $Form->where('id=3')-> ;getField('title');The above usage means to get the title field value of the data with id value 3. In fact, the getField method has many uses, but getting the value of a certain field is the most common use of the getField method.Query operation is the most commonly used operation, especially when it involves complex query conditions. We will explain query in more detail in the query language chapter.
Update data
After successfully writing and reading the data, we can edit the data. First, we add a template file edit.html for the editing form, as follows:
Editing a template is different from adding a new form. The template needs to be assigned variables, so we need to add two operation methods to the FormAction class this time:
public function edit($id=0){
$Form = M('Form');
$this ->vo = $Form->find($id);
$this->display();
}
public function update(){
$Form = D('Form');
if($Form->create()) {
$result = $Form->save();
if($result) {
$this-> success('Operation successful!' ; t;getError()) ;
}
}
Once completed, we can access
http://localhost/app/index.php/Form/edit/id/1
The data update operation uses the save method in ThinkPHP. You can see that we can also use the create method to create the data submitted by the form. , and the save method will automatically update the current data object to the database, and the update condition is actually the primary key of the table. This is why we submit the value of the primary key as a hidden field on the edit page.
If the update operation does not rely on the submission of the form, it can be written as:
$Form = M("Form");
// Assignment of the data object attributes to be modified
$data['id'] = 5;
$data['title'] = 'ThinkPHP';
$data['content'] = 'ThinkPHP3.1 version released';
$Form->save($data); // Save according to conditions The modified data
save method will automatically identify the primary key field in the data object and use it as an update condition. Of course, you can also explicitly pass in the update conditions:
$Form = M("Form");
// Assign the data object attribute to be modified
$data['title'] = 'ThinkPHP';
$data['content'] = 'ThinkPHP3.1 version released';
$Form->where('id=5')->save($data); // Save modified data according to conditions
You can also change it to object mode:
$Form = M("Form");
//Assign the data object attribute to be modified
$Form->title = 'ThinkPHP';
$ Form->content = 'ThinkPHP3.1 version released';
$Form->where('id=5')->save(); // Save modified data according to conditions
data object assignment method, the save method does not need to pass in data, it will be automatically recognized. The return value of the
save method is the number of records affected. If false is returned, it means an update error.
Sometimes, we only need to modify the value of a certain field and use the setField method instead of calling the save method every time.
$Form = M("Form");
//Change title value
$Form->where('id=5')->setField('title','ThinkPHP');
For statistical fields, the system also provides more convenient setInc and setDec methods.
For example:
$User = M("User"); // Instantiate the User object
$User->where('id=5')->setInc('score',3); // The user's points are increased by 3
$User->where('id=5')->setInc('score'); // The user's points are increased by 1
$User->where('id=5 ')->setDec('score',5); // The user's points are reduced by 5
$User->where('id=5')->setDec('score'); // The user's points Points minus 1
Delete data
Deleting data is very simple, just call the delete method, for example:
$Form = M('Form');
$Form->delete(5);
Indicates deleting data with a primary key of 5. The delete method can delete a single data or multiple data, depending on the deletion conditions, for example:
$User = M("User"); // Instantiate the User object
$User->where('id=5')->delete(); // Delete the user data with id 5
$User->delete('1,2,5'); // Delete User data with primary keys 1, 2 and 5
$User->where('status=0')->delete(); // Delete all user data with status 0
The return value of the delete method is The number of deleted records. If the return value is false, it means an SQL error occurred. If the return value is 0, it means no data was deleted.
Summary
Now, you have basically mastered ThinkPHP's CURD operation, and learned to use ThinkPHP's create, add, save and delete methods, as well as the two getField and setField methods for field operations. In the next article, we will take a deeper look at how to use the query language provided by ThinkPHP.
The above is the content of ThinkPHP3.1 Quick Start (2) Data CURD. For more related content, please pay attention to the PHP Chinese website (www.php.cn)