ThinkPHP3.1 Quick Start (2) Data curd

Source: Internet
Author: User
Tags define array definition insert php file query sql error variable

In the previous article, we learned the basics of thinkphp, how to create a controller and template, and know the use of the M method, this article will explain the data of the curd operation, explore the next more data operations.

Curd

Curd is a database technology acronym, the General Project development of the basic functions of various parameters are curd. It represents create, update, read (read), and delete (delete) operations. Curd defines the basic atomic operations that are used to process data. The elevation of curd to a technical challenge is due to the completion of a summary-related activity involving curd operations in multiple database systems, whose performance may vary greatly depending on the data relationship.
Curd does not necessarily use the word create, update, read, and delete methods in specific applications, but they accomplish the same function. For example, thinkphp is a curd operation that uses the Add, save, select, and Delete methods to represent the model.

Creating Data

In most cases, the curd create operation usually submits the data through the table forms, first of all, we created a add.html template file under the Tpl/form directory of the project, which reads:

    1. <form method= "POST" action= "__url__/insert" >
    2. Title: <input type= "text" name= "title" ><br/>
    3. Content: <textarea name= "Content" rows= "5" cols= "></TEXTAREA><br/>"
    4. <input type= "Submit" value= "submitted" >
    5. </FORM>

Then, we also need to create a FormAction.class.php file under the project's action directory, temporarily define only the FormAction class, and do not need to add any action methods, the code is as follows:

    1. Class FormAction extends action{
    2. }

Next, visit

    1. Http://localhost/app/index.php/Form/add

You can see the form page, we don't define the Add action method in the controller, but obviously the access is normal. Because thinkphp does not find the corresponding operation method, will check whether there is a corresponding template file, because we have the corresponding add template file, so the controller directly renders the template file output. So for the operation without any practical logic, we just need to define the corresponding template file directly.
As we can see, in the form, where the submit address is defined as an insert to the form module, we need to add the insert operation method to the FormAction class in order to process the form submission data as follows:

  1. Class FormAction extends action{
  2. Public Function Insert () {
  3. $Form = D (' Form ');
  4. if ($Form->create ()) {
  5. $result = $Form->add ();
  6. if ($result) {
  7. $this->success (' Operation successful! ');
  8. }else{
  9. $this->error (' Write Error! ');
  10. }
  11. }else{
  12. $this->error ($Form->geterror ());
  13. }
  14. }
  15. }

If your primary key is a self increasing type, the return value of the Add method is the value of that primary key. is not a self-added primary key, the return value represents the number of inserted data. If False, it indicates a write error.

Model

To facilitate testing, we first create a think_form table in the database:

    1. CREATE TABLE IF not EXISTS ' Think_form ' (
    2. ' ID ' smallint (4) unsigned not NULL auto_increment,
    3. ' title ' varchar (255) Not NULL,
    4. ' Content ' varchar (255) Not NULL,
    5. ' Create_time ' int (one) unsigned not NULL,
    6. PRIMARY KEY (' id ')
    7. ) Engine=myisam DEFAULT Charset=utf8;

We use the D function in the Insert method, unlike the M function, the D function requires a corresponding model class, and we then create the model class. The definition specification for the Model class is: Model name +model.class.php (the definition of the model name is the Hump method and the first letter is capitalized)
We created the FormModel.class.php file under the Lib/model directory of the project, adding the following code:

    1. class formmodel extends model {
    2.     //  define automatic validation
    3.     protected $_validate    =   array (
    4.         array (' title ', ' Require ', ' title must '),
    5.          );
    6.     //  Definition Auto-complete
    7.     protected $_auto    =   array (
    8.         array (' Create_time ', ' time ', 1, ' function '),
    9.          );
    10. }

Mainly for the automatic verification of forms and automatic completion, the specific use we will use another space alone, here for the moment skip. All we have to understand is that if you instantiate the model class using the D function, you typically need to correspond to a data model class, and the Create method automatically validates and automates the data submitted by the form (if it is defined), and if automatic validation fails, You can get the validation hint through the GetError method of the model, and if the validation passes, it means that the data object has been created successfully, but is currently only 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 the data:
The first step, the Create method creates the data object,
The second step is to use the Add method to write the current data object to the database.
Of course, you can go through the first step and take the second step directly, but there are several advantages to this preprocessing:
1, no matter how complex the form, create method can use a line of code easily created data objects;
2. Before the data is written, the data can be validated and supplemented;
In fact, the Create method also has a lot of functional operations, the purpose is only one, to ensure that the data written to the database is safe and effective.
We verify the effect of the form submission, and when we submit the form directly without entering the title, the system gives the message that the title must be. When we successfully submit the form, we see that the Create_time field in the data that is written to the data table already has a value, which is written by the automatic completion of the model. If your data is written entirely internally rather than through the form (that is, you can fully trust the security of the data), you can use the Add method directly, such as:

    1. $Form = D (' Form ');
    2. $data [' title '] = ' thinkphp ';
    3. $data [' content '] = ' form contents ';
    4. $Form->add ($data);

You can also support object-mode operations:

    1. $Form = D (' Form ');
    2. $Form->title = ' thinkphp ';
    3. $Form->content = ' form content ';
    4. $Form->add ();

Object, the Add method automatically recognizes the current assignment of data objects without having to pass in data.

reading Data

When we successfully write the data, we can do the data read operation. In the previous article, we already know that we can get a dataset using the Select method, where we get a single piece of data by using the Find method, which defines the read action method as follows:

    1. Public function read ($id =0) {
    2. $Form = M (' Form ');
    3. Reading data
    4. $data = $Form->find ($id);
    5. if ($data) {
    6. $this->data = $data;//Template variable assignment
    7. }else{
    8. $this->error (' data error ');
    9. }
    10. $this->display ();
    11. }

The read operation method has a parameter $id, which means we can accept the ID variable in the URL (we'll describe it in detail later in the variable section.) The M method is not used here because the Find method is the method in the basic model class mode, so there is no need to waste overhead to instantiate the Formmodel class (even if the Formmodel class is already defined). We usually use the Find method to read a data, where the AR mode is used to operate, so there is no incoming query condition, the search ($id) represents the reading of the primary key to the $id value of the data, the lookup method return value is an array of the following format:

    1. Array
    2. ' ID ' => 5,
    3. ' title ' => ' Test headline ',
    4. ' Content ' => ' test contents ',
    5. ' Status ' => 1,
    6. )

Then we can output the data in the template, add a read template file,

    1. <table>
    2. <tr>
    3. <td>id:</td>
    4. <td>{$data .id}</td>
    5. </tr>
    6. <tr>
    7. <td> title:</td>
    8. <td>{$data .title}</td>
    9. </tr>
    10. <tr>
    11. <td> content:</td>
    12. <td>{$data .content}</td>
    13. </tr>
    14. </table>

Upon completion, we will be able to access

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

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

    1. $Form = M ("Form");
    2. Get title
    3. $title = $Form->where (' id=3 ')->getfield (' title ');

The above usage represents the Title field value of the data that gets the ID value of 3. In fact, the GetField method has many uses, but getting a field's value is the most common use of the GetField method.
Query operations are the most commonly used operations, especially involving complex query conditions, we will be in the query Language chapter of the query for more detailed explanation.

Update Data

After the data is successfully written and read, we can edit the data, first we add a template file to edit the form edit.html, as follows:

    1. <form method= "POST" action= "__url__/update" >
    2. Title: <input type= "text" name= "title" Value= "{$vo. Title}" ><br/>
    3. Content: <textarea name= "Content" rows= "5" cols= "" >{$vo .content}</textarea><br/>
    4. <input type= "hidden" name= "id" value= "{$vo. ID}" >
    5. <input type= "Submit" value= "submitted" >
    6. </FORM>

Editing templates are different from new forms, and you need to assign variables to the template, so we need to add two actions to the FormAction class this time:

  1. Public function edit ($id =0) {
  2. $Form = M (' Form ');
  3. $this->vo = $Form->find ($id);
  4. $this->display ();
  5. }
  6. Public Function Update () {
  7. $Form = D (' Form ');
  8. if ($Form->create ()) {
  9. $result = $Form->save ();
  10. if ($result) {
  11. $this->success (' Operation successful! ');
  12. }else{
  13. $this->error (' Write Error! ');
  14. }
  15. }else{
  16. $this->error ($Form->geterror ());
  17. }
  18. }

Upon completion, we will be able to access

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

The update operation of the data uses the Save method in thinkphp, and you can see that we can also create the data submitted by the form by using the Create method, while the Save method automatically updates the current data object to the database, and the updated condition is actually the primary key of the table. That's why we're going to edit the page to submit the value of the primary key as a hidden field.
If the update operation does not depend on the form's submission, it can be written as:

    1. $Form = M ("Form");
    2. The data object property assignment to modify
    3. $data [' id '] = 5;
    4. $data [' title '] = ' thinkphp ';
    5. $data [' content '] = ' ThinkPHP3.1 release ';
    6. $Form->save ($data); Save modified data based on criteria

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

    1. $Form = M ("Form");
    2. The data object property assignment to modify
    3. $data [' title '] = ' thinkphp ';
    4. $data [' content '] = ' ThinkPHP3.1 release ';
    5. $Form->where (' id=5 ')->save ($data); Save modified data based on criteria

can also be changed to Object mode:

    1. $Form = M ("Form");
    2. The data object property assignment to modify
    3. $Form->title = ' thinkphp ';
    4. $Form->content = ' ThinkPHP3.1 release ';
    5. $Form->where (' id=5 ')->save (); Save modified data based on criteria

The way the data object is assigned, the Save method is automatically recognized without the need to pass in data.
The return value of the Save method is the number of records affected and, if False, indicates an update error.

Sometimes we just need to modify the value of a field to use the SetField method without having to call the Save method every time.

    1. $Form = M ("Form");
    2. Change title Value
    3. $Form->where (' id=5 ')->setfield (' title ', ' thinkphp ');

For statistical fields, the system also provides a more convenient Setinc and Setdec method.
For example:

    1. $User = M ("User"); Instantiating the User object
    2. $User->where (' id=5 ')->setinc (' Score ', 3); User's integral plus 3
    3. $User->where (' id=5 ')->setinc (' score '); User's integral plus 1
    4. $User->where (' id=5 ')->setdec (' Score ', 5); User's points minus 5
    5. $User->where (' id=5 ')->setdec (' score '); User's points minus 1

Delete Data

Deleting data is simple, and you just need to call the Delete method, for example:

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

Represents the deletion of data from a primary key of 5, which deletes a single data or deletes multiple data, depending on the criteria for deletion, such as:

    1. $User = M ("User"); Instantiating the User object
    2. $User->where (' id=5 ')->delete (); Delete user data with ID 5
    3. $User->delete (' 1,2,5 '); Delete user data with primary keys of 1, 2, and 5
    4. $User->where (' status=0 ')->delete (); Delete all user data with a status of 0

The return value of the Delete method is the number of records deleted, and if the return value is false, a SQL error, and a return value of 0 indicates that no data has been deleted.

Summary

Now that you have mastered the curd of thinkphp, you have learned to use the thinkphp Create, add, save, and Delete methods, as well as two GetField and SetField methods for field operations. Next, we'll take a closer look at how to use the query language provided by thinkphp.



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.