Summary of ThinkPHP data operations

Source: Internet
Author: User
Tags php mysql
This article mainly introduces ThinkPHP data operation methods and summarizes ThinkPHP's implementation techniques for adding, updating, querying, and deleting data in the form of instances. it has some reference value, for more information about how to operate ThinkPHP data, see the examples in this article. Share it with you for your reference. The details are as follows:

I. add data using ThinkPHP Insert

The built-in add method of ThinkPHP is used to add data to a data table, which is equivalent to the insert into action in SQL.

Add data using the Create method in CURD (Create, Update, Read, Delete/Create, modify, Read, and Delete, thinkPHP supports writing data into a data table in the form of a common array and object-oriented mode.

Take the example of operating user table data in PHP MySQL database tutorial (for details, see Insert Into data insertion usage analysis in PHP + MySQL, to demonstrate how to add data to a data table in ThinkPHP.

Example:

In the IndexAction controller (Lib/Action/IndexAction. class. php), add the insert () operation:

Public function insert () {header ("Content-Type: text/html; charset = utf-8"); $ Dao = M ("User "); // instantiate the model class // Construct the written data array $ data ["username"] = "John"; $ data ["password"] = md5 ("123456 "); $ data ["email"] = 12345@163.com; $ data ["regdate"] = time (); // write data if ($ lastInsId = $ Dao-> add ($ data) {echo "insert data id: $ lastInsId ";} else {$ this-> error ('data writing error! ');}}

Access and perform this operation: http: // 127.0.0.1/html/Myapp/index. php/Index/insert

Grammar explanation

M ("User") is used to efficiently instantiate a data Model (M is short for the new Model, called a shortcut). the parameter is the name of the table to be operated.

Next, we construct the array $ data to save the data.

Finally, the add () method is used to write data into the database table. because the M shortcut method is used, the $ data array needs to be passed into the add () method.

If the data record is successfully added by the add () method, the primary key of the new data record is returned, which can be obtained directly.
In this example, the actual running SQL is:

Insert into user (username, password, email, regdate) VALUES ('John ', 'e10adc3949ba59abbe56e057f20f883e', '2017 @ 163.com ', 12345)

Tip: run this example. make sure that the related account and password of the database are correctly configured in the configuration file. for details, see ThinkPHP public configuration file and configuration file combination in their respective projects.

Add data as an object

The above method is to construct an array of data, and then input the data in the form of parameters into the add method to write the data table. ThinkPHP also supports writing data into the data table as an object and changing the above code:

Public function insert () {header ("Content-Type: text/html; charset = utf-8"); $ Dao = M ("User "); // instantiate model class // value $ Dao-> username = ""; $ Dao-> password = md5 ("123456 "); $ Dao-> email = 12345@163.com; $ Dao-> regdate = time (); // write data if ($ lastInsId = $ Dao-> add ()) {echo "insert data id: $ lastInsId";} else {$ this-> error ('data writing error! ');}}

In addition to assigning values to data objects, you do not need to pass parameters when calling the add method to write data.

II. save method for ThinkPHP to update data

Save ()

The save () method is used in ThinkPHP to update the database, and consistent operations are also supported.
Example:

Public function update () {header ("Content-Type: text/html; charset = utf-8"); $ Dao = M ("User "); // the data to be updated $ data ['email '] = 'Jack @ 163.com'; // The Updated condition $ condition ['username'] = 'Jack '; $ result = $ Dao-> where ($ condition)-> save ($ data); // Or: $ resul t = $ Dao-> where ($ condition) -> data ($ data)-> save (); if ($ result! = False) {echo 'data updated successfully! ';} Else {echo' data update failed! ';}}

The SQL statement executed in the preceding example is:

UPDATE user SET email = 'Jack @ 163.com 'WHERE username = 'Jack'

Prompt

To ensure database security and avoid errors in updating the entire data table, if the data object itself does not contain the primary key field, the save method will not update any database records.

Therefore, to update data using the save () method, you must specify the update condition or the updated data contains the primary key field.

Example of using a primary key:

Public function update () {header ("Content-Type: text/html; charset = utf-8"); $ Dao = M ("User "); // the data to be updated $ data ['email '] = 'Jack @ 163.com'; $ data ['uid'] = 2; $ result = $ Dao-> save ($ data); if ($ result! = False) {echo 'data updated successfully! ';} Else {echo' data update failed! ';}}

If the data to be updated contains the primary key, ThinkPHP automatically updates the value of the primary key as a condition.

The above example has the same effect as the following:

// The data to be updated $ data ['email '] = 'Jack @ 163.com ';
// Updated condition $ condition ['uid'] = 2; $ result = $ Dao-> where ($ condition)-> save ($ data );
For form data, you can also use the create () method to create a data object to update the data:

Public function update () {header ("Content-Type: text/html; charset = utf-8"); $ Dao = D ("User "); if ($ vo = $ Dao-> create () {$ result = $ Dao-> save (); if ($ result! = False) {echo 'data updated successfully! ';} Else {echo' data update failed! ';}} Else {$ this-> error ($ Form-> getError ());}}

If the updated data requires logical processing, you can process the data in the operation class as an object or in the model. for details, refer to the ThinkPHP create method for smart data writing.

Note: the create () method is used to create a data object to update the data. The form must contain a hidden field named by the primary key to complete the SAVE operation.

III. select (findAll) method for data query in ThinkPHP

ThinkPHP provides the following types of data query:
Select: normal query, same as the findAll () method
Find: obtain a record that meets the query conditions.
GetBy dynamic query: obtains a record that meets the query conditions based on a field.
GetField: obtains the value of a field or the index array of multiple fields.
Interval query: obtain the interval records that meet the query conditions.
Statistical query: obtains statistics that meet the query conditions.
Locate query: obtain one or more records that meet the query conditions.
Native SQL query: supports querying or performing operations with native SQL

Select ()

Select () is the most common query method in ThinkPHP, and a two-dimensional array is obtained. FindAll () is the alias of the select () method. we recommend that you use select ().

Read operation

In the following example, all data in the user table is read and displayed:

Public function read () {$ Dao = M ("User"); // query data $ list = $ Dao-> select (); // dump ($ list ); // with dump (), you can check whether the data has been read in the debugging phase. // The template variable is assigned $ this-> assign ("list", $ list ); // output template $ this-> display ();}

Assume that the class file corresponding to the above example is Lib/Action/IndexAction. class. php, then the corresponding template file is Tpl/default/Index/read.html.

Data Display template

The template file is used to display the data in the read User table. In the learning phase, you can directly use the foreach syntax to directly display the read data in the read () operation if you do not want to use the template. The following is the code snippet of the template. the read data is displayed in a table:

 
 
 
ID User name Email Registration time
{$ Vo ['uid']} {$ Vo ['username']} {$ Vo ['email ']} {$ Vo ['regdate'] | date = 'Y-m-d H: I ',###}

To learn more

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.