ThinkPHP3.1 Data CURD Operation Quick Start

  • 2021-07-01 07:04:46
  • OfStack

1. CURD overview:

CURD is an abbreviation in database technology, and the basic functions of various parameters developed by a general project are CURD. It represents the Create (Create), Update (Update), Read (Read), and Delete (Delete) operations. CURD defines basic atomic operations for processing data. The reason why CURD is raised to the level of a technical problem is that the performance of completing a summary-related activity involving CURD operations in multiple database systems may vary greatly depending on the data relationship.

CURD does not necessarily use the words create, update, read and delete in specific applications, but their functions are unique. For example, ThinkPHP is an CURD operation that represents the model using add, save, select, and delete methods.

Step 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/Form directory of the project with the content:


<FORM method="post" action="__URL__/insert">
 Title: <INPUT type="text" name="title"><br/>
 Content: <TEXTAREA name="content" rows="5" cols="45"></TEXTAREA><br/>
 <INPUT type="submit" value=" Submit ">
 </FORM>

Then, we also need to create an FormAction. class. php file under the Action directory of the project. For the time being, we only need to define the FormAction class without adding any operation methods. The code is as follows:


class FormAction extends Action{
 }

Next, visit:


http://localhost/app/index.php/Form/add

You can see the form page. We didn't define the add operation method in the controller, but obviously, the access is normal. Because ThinkPHP does not find the corresponding operation method, it will check whether there is a corresponding template file. Because we have a corresponding add template file, the controller directly renders the template file and outputs it. Therefore, for the operation method without any actual logic, we only need to directly define the corresponding template file.
We can see that the insert operation whose submission address is to the Form module is defined in the form. In order to process the form submission data, we need to add the insert operation method to the FormAction class, as follows:


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 self-increasing type, the return value of the add method is the value of that primary key. If it is not a self-increasing primary key, the return value indicates the number of inserted data. If false is returned, it indicates a write error.

3. Models

To facilitate testing, we first create an 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 D function in insert operation method. Unlike M function, D function needs corresponding model class. Let's create model class below. The definition specification of model classes is:
Model name + Model. class. php (Model name is defined by hump method and initials are capitalized)
We created the FormModel. class. php file under the project's Lib/Model directory, adding the following code:


class FormModel extends Model {
  //  Define automatic validation 
  protected $_validate  =  array(
    array('title','require',' The title must '),
    );
  //  Define auto-completion 
  protected $_auto  =  array(
    array('create_time','time',1,'function'),
    );
 }

It is mainly used for automatic verification and automatic completion of forms. We will talk about the specific usage separately in another space, which will be skipped here for the time being. All we need to know is, If you use the D function to instantiate a model class, 1 generally needs to correspond to 1 data model class, And the create method automatically validates and completes the data submitted by the form (if defined), If the automatic validation fails, you can get the validation prompt information through the getError method of the model. If the validation passes, it means that the data object has been successfully created, but it is 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:

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

Of course, you can go beyond Step 1 and go straight to Step 2, but this pretreatment has several advantages:

1. No matter how complex the form is, the create method can easily create data objects with one line of code;
2. Before writing the data, the data can be verified and supplemented;
In fact, create method still has many functional operations, with only one purpose to ensure the safety and effectiveness of data written into the database.

Let's verify the effect of the following form submission. When we submit the form directly without entering the title, the system will give a prompt message 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 auto-completion of the model.

If your data is written completely internally instead of through a form (that is, you can fully trust the security of the data), you can directly use add methods, such as:


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

Object mode operation can also be supported:


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

Object mode, the add method does not need to pass in data, and will automatically recognize the current data object assignment.

Step 4 Read the data

When we successfully write the data, we can read the data. In the previous article, we already know that the data set can be obtained by select method. Here, we will obtain a single 1 data by find method, and define the operation method of read as follows:


public function read($id=0){
  $Form  =  M('Form');
  //  Read data 
  $data =  $Form->find($id);
  if($data) {
    $this->data =  $data;//  Template variable assignment 
  }else{
    $this->error(' Data error ');
  }
  $this->display();
 }

The read operation method has a parameter $id, which means that we can accept the id variable in URL (which will be described in detail in the Variables section later. The reason for using the M method instead of the D method here is that the find method is a method in the underlying model class Model, so there is no need to waste the overhead of instantiating the FormModel class (even if the FormModel class has been defined). We usually use find method to read some data. Here, we use AR mode to operate, so there is no query condition passed in. find ($id) means reading data with a primary key of $id. The return value of find method is an array in the following format:


array(
  'id'    => 5,
  'title'   => ' Test title ',
  'content'  => ' Test content ',
  'status'  => 1,
 )

Then we can output the data in the template and add an read template file:


class FormAction extends Action{
 }

0

When we're done, we can access


class FormAction extends Action{
 }

1

Come and check it out.
If you only need to query the value of a field, you can also use getField methods, such as:


class FormAction extends Action{
 }

2

The above usage means to get the value of the title field for data with an id value of 3. In fact, the getField method has many uses, but getting the value of a field is the most common use of the getField method.
Query operations are the most commonly used operations, especially when it comes to complex query conditions. We will explain queries in more detail in Chapter 1 of Query Language.

Step 5 Update data

After successfully writing and reading the data, we can edit the data. First, we add a template file edit. html for editing the form, as follows:


 <FORM method="post" action="__URL__/update">
   Title: <INPUT type="text" name="title" value="{$vo.title}"><br/>
   Content: <TEXTAREA name="content" rows="5" cols="45">{$vo.content}</TEXTAREA><br/>
  <INPUT type="hidden" name="id" value="{$vo.id}">
  <INPUT type="submit" value=" Submit ">
 </FORM>

Editing a template is different from adding a form, and you need to assign variables to the template, so we need to add two operation methods to the FormAction class this time:


class FormAction extends Action{
 }

4

When we're done, we can access


class FormAction extends Action{
 }

5


The data update operation uses save method in ThinkPHP. As you can see, we can also use create method to create the data submitted by the form, while save method will automatically update the current data object to the database, and the update condition is actually the primary key of the table, which is why we want to submit the value of the primary key as a hidden field 1 on the editing page.
If the update operation does not depend on the submission of the form, it can be written as:


class FormAction extends Action{
 }

6

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


class FormAction extends Action{
 }

7

You can also change it to object mode:


$Form = M("Form"); 
 //  Data object property assignment to be modified 
$Form->title = 'ThinkPHP';
$Form->content = 'ThinkPHP3.1 Version release ';
$Form->where('id=5')->save(); //  Save modified data according to conditions 

The way data objects are assigned, save method does not need to pass in data, will automatically identify.
The return value of the save method is the number of records affected, and returning false indicates an update error.

Sometimes we can use the setField method just by modifying the value of a field instead of calling the save method every time.


class FormAction extends Action{
 }

9

For statistical fields, the system also provides more convenient setInc and setDec methods.
For example:


  $User = M("User"); //  Instantiation User Object 
  $User->where('id=5')->setInc('score',3); //  User's points plus 3
  $User->where('id=5')->setInc('score'); //  User's points plus 1
  $User->where('id=5')->setDec('score',5); //  User's integral minus 5
  $User->where('id=5')->setDec('score'); //  User's integral minus 1


Step 6 Delete data

Deleting data is simple, and you only need to call the delete method, for example:


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

To delete data with a primary key of 5, the delete method can delete a single data or multiple data, depending on the deletion conditions, such as:


$User = M("User"); //  Instantiation User Object 
$User->where('id=5')->delete(); //  Delete id For 5 User data of 
$User->delete('1,2,5'); //  Delete primary key as 1,2 And 5 User data of 
$User->where('status=0')->delete(); //  Delete all items with the status of 0 User data of 

The return value of the delete method is the number of records deleted. If the return value is false, it means that SQL has an error, and if the return value is 0, it means that no data has been deleted.


Related articles: