ThinkPHP3.1 quick start to data CURD operations

Source: Internet
Author: User
Tags sql error
This article mainly introduces the CURD operation of ThinkPHP3.1. For more information, see ThinkPHP.

1. CURD overview:

CURD is a acronym in database technology. Generally, the basic functions of various parameters in project development are CURD. It represents Create, Update, Read, and Delete operations. CURD defines the basic atomic operations used to process data. The reason for increasing CURD to a technical difficulty is that it completes a summary-related activity involving performing CURD operations in multiple database systems, its performance may vary greatly with the changes in data relationships.

CURD does not necessarily use the create, update, read, and delete methods in specific applications, but their functions are consistent. For example, ThinkPHP uses the add, save, select, and delete methods to represent the CURD operations of the model.

2. create data

In most cases, the Create operation of CURD usually submits data through a form. First, we Create an add.html template file under the Tpl/formdirectory of the project. the content is:

 

Then, we also need to create a FormAction. class. php file under the Action Directory of the project. Currently, 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

We can see the form page. we didn't define the add operation method in the controller, but obviously, access is normal. Because ThinkPHP does not find the corresponding operation method, it will check whether the corresponding template file exists. because we have the corresponding add template file, therefore, the controller directly renders the template file output. Therefore, if there is no actual logical operation method, we just need to define the corresponding template file.
We can see that the submitted address is defined in the Form as the insert operation to the Form module. to process the data submitted by the Form, we need to add the insert operation method to the FormAction class, as shown below:

Class FormAction extends Action {public function insert () {$ Form = D ('form'); if ($ Form-> create ()) {$ result = $ Form-> add (); if ($ result) {$ this-> success ('Operation successful! ');} Else {$ this-> error ('write error! ') ;}} Else {$ this-> error ($ Form-> getError ());}}}

If your primary key is of the auto-increment type, the return value of the add method is the value of the primary key. If it is not an auto-increment primary key, the return value indicates the number of inserted data. If false is returned, a write error occurs.

3. model

To facilitate the test, 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 use the D function in the insert operation method. Unlike the M function, the D function requires a corresponding model class. next we will create a model class. The model class definition specification is:
Model Name + Model. class. php (the Model name is defined using the hump method and the first letter is capitalized)
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 verification protected $ _ validate = array ('title', 'require ', 'title '),); // define automatically completed protected $ _ auto = array ('create _ time', 'time', 1, 'Function '),);}

It is mainly used for automatic form verification and automatic completion. the specific usage will be described separately in other sections. I will skip this section for the time being. We only need to know that if we use the D function to instantiate a model class, we usually need to correspond to a data model class, in addition, the create method automatically verifies and completes the data submitted by the form (if defined). If the automatic verification fails, you can obtain the verification prompt information through the getError method of the model, if the verification succeeds, it indicates that the data object has been successfully created, but is currently only saved in the memory until we call the add method to write data to the database. This completes a complete Create operation, so we can see that ThinkPHP uses two steps during data creation:

Step 1: create a data object using the create method,
Step 2: Use the add method to write the current data object to the database.

Of course, you can go through Step 1 and Step 2 directly, but such preprocessing has several advantages:

1. no matter how complicated the form is, the create method can easily create data objects with a line of code;
2. data can be verified and supplemented before being written;
In fact, the create method also has many functional operations with only one purpose to ensure the security and effectiveness of data written into the database.

Let's verify the form submission effect. when we directly submit the form without entering the title, the system will give a prompt message that the title must be like this.
After successfully submitting the form, we can see that the create_time field in the data written to the data table already has a value, which is automatically written through the model.

If your data is completely written by internal operations rather than through forms (that is to say, you can fully trust data security), you can directly use the add method, such:

$ Form = D ('form'); $ data ['title'] = 'thinkphp'; $ data ['content'] = 'form content '; $ Form-> add ($ data );

You can also perform the following operations on objects:

$ Form = D ('form'); $ Form-> title = 'thinkphp'; $ Form-> content = 'form content'; $ Form-> add ();

During object operations, the add method automatically recognizes the assignment of the current data object without passing in data.

4. read data

After data is successfully written, you can read the data. In the previous article, we know that you can use the select method to obtain a dataset. here we use the find method to obtain a single data. 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 value assignment} else {$ this-> error ('data error ');} $ this-> display ();}

The read operation method has a parameter $ id, indicating that we can accept the id variable in the URL (which will be described in the variable section later. Here, the M method is used instead of the D method, because the find method is the method in the Model of the basic Model class, so there is no need to waste the overhead to instantiate the FormModel class (even if the FormModel class has been defined ). We usually use the find method to read a data. here we use the AR mode for operations, so no query conditions are passed in. find ($ id) indicates to read data whose primary key is $ id, 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:

 
 
Id: {$ Data. id}
Title: {$ Data. title}
Content: {$ Data. content}

Then, we can access

http://localhost/app/index.php/Form/read/id/1

.
If you only need to query the value of a field, you can also use the getField method, for example:

$ Form = M ("Form"); // Obtain the title $ title = $ Form-> where ('Id = 3')-> getField ('title ');

The above usage indicates obtaining the title field value of the data whose id value is 3. In fact, the getField method has many usage, but obtaining the value of a field is the most common usage of the getField method.
Query operations are the most common operations, especially when complicated query conditions are involved. we will explain the query in more detail in the query language chapter.

5. update data

After successfully writing and reading data, we can edit the data. First, we need to edit the template file edit.html of the table, as shown below:

 

Editing a template is different from adding a form. you need to assign values to the template variables. Therefore, we need to add two operation methods in 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! ');} Else {$ this-> error ('write error! ') ;}} Else {$ this-> error ($ Form-> getError ());}}

Then, we can access

http://localhost/app/index.php/Form/edit/id/1


The data update operation in ThinkPHP uses the save method. we can also use the create method to create the data submitted by the form. the save method automatically updates the current data object to the database, the update condition is actually the table's primary key, which is why we need to submit the primary key value as a hidden field on the editing page.
If the update operation does not rely on form submission, it can be written:

$ Form = M ("Form"); // the attribute value of the data object to be modified is $ data ['id'] = 5; $ data ['title'] = 'thinkphp'; $ data ['content'] = 'thinkphp3. 1 Release '; $ Form-> save ($ data); // save the modified data according to the conditions

The save method automatically identifies the primary key field in the data object and serves as the update condition. Of course, you can also explicitly pass in the update conditions:

$ Form = M ("Form"); // the attribute value of the data object to be modified is $ data ['title'] = 'thinkphp '; $ data ['content'] = 'thinkphp3. 1 Release '; $ Form-> where ('Id = 5')-> save ($ data); // save the modified data according to the conditions

You can also change it to an object:

$ Form = M ("Form"); // the attribute value of the data object to be modified is $ Form-> title = 'thinkphp'; $ Form-> content = 'thinkphp3. 1 Release '; $ Form-> where ('Id = 5')-> save (); // save the modified data according to the conditions

The method of assigning values to data objects. the save method automatically recognizes data without passing in data.
The return value of the save method is the number of affected records. if false is returned, an update error occurs.

Sometimes, you only need to modify the value of a field to use the setField method, instead of calling the save method every time.

$ Form = M ("Form"); // change the title value $ Form-> where ('Id = 5')-> setField ('title', 'thinkphp ');

The system also provides more convenient setInc and setDec methods for statistical fields.
For example:

$ User = M ("User"); // instantiate the User object $ User-> where ('Id = 5')-> setInc ('score ', 3 ); // add 3 $ User-> where ('Id = 5')-> setInc ('score '); // add 1 $ User-> where ('Id = 5')-> setDec ('score ', 5 ); // reduce the User's points by 5 $ User-> where ('Id = 5')-> setDec ('score '); // reduce the User's points by 1


6. delete data

To delete data, you only need to call the delete method. for example:

$Form = M('Form');$Form->delete(5);

Indicates that data with the primary key of 5 can be deleted. The delete method can delete a single data or multiple data, depending on the deletion conditions, such:

$ User = M ("User"); // instantiate the User object $ User-> where ('Id = 5')-> delete (); // delete User data with id 5 $ User-> delete ('1, 2, 5 '); // delete User data whose primary key is 1, 2, and 5 $ User-> where ('status = 0')-> delete (); // delete all User data whose status is 0

The return value of the delete method is the number of deleted records. if the return value is false, an SQL error occurs. if the return value is 0, no data is deleted.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.