This paper summarizes the methods of thinkphp data operation. Share to everyone for your reference. Specific as follows:
One, thinkphp Insert add data
The thinkphp built-in Add method is used to add data to the data table, equivalent to the INSERT into behavior in SQL.
Adding the Data add method is the implementation of create in curd (Create,update,read,delete/Create, modify, read, delete), thinkphp supports writing data to the data table in a normal array and object-oriented manner.
Now take the example of manipulating the user table data in the PHP MySQL database tutorial (see: Php+mysql INSERT INTO Data insertion usage analysis) to demonstrate how to add operations to data tables 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//build the data array to write $data ["username"] = "Xiao Wang"; $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 write Error! ');}}
Access to perform this operation: Http://127.0.0.1/html/Myapp/index.php/Index/insert
Grammatical interpretation
M ("User") is used to efficiently instantiate a data model (M is shorthand for the new model, called the shortcut method), and the parameter is the name of the table to be manipulated.
Next, build the array $data to hold the data.
Finally, using the Add () method to write the data into the table, because the use of the M shortcut method, you need to pass the $DATA array into the Add () method.
Add () method if the data record is added successfully, the new data record primary key is returned, which can be obtained directly.
This example actually runs the SQL:
INSERT into User (username,password,email,regdate) VALUES (' Xiao Wang ', ' e10adc3949ba59abbe56e057f20f883e ', ' 12345@163.com ', 1283612673)
Tip: To run this example, make sure that the relevant account password for the database is correctly configured in the configuration file, see the thinkphp Common configuration file and the method of configuration file combination in the respective project.
Object way to add data
The method above is to construct the data array, and then pass the data to the Add method as a parameter to write to the data table. Thinkphp also supports writing data to the data table as an object, changing the code above to:
Public Function Insert () {header ("content-type:text/html; Charset=utf-8 "); $Dao = M ("User"); Instantiate model class//Data Object Assignment $dao->username = "Xiao Wang"; $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 write Error! '); }}
Object Mode In addition to assigning data as data objects, you do not need to pass parameters when calling the Add method to write data.
Second, thinkphp Update data Save method
Save ()
The Save () method is used in thinkphp to update the database and also supports the use of coherent operations.
Example:
Public Function Update () {header ("content-type:text/html; Charset=utf-8 "); $Dao = M (" User "); Data needs to be updated $data [' email '] = ' Jack@163.com ';//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 by the example above is:
UPDATE user SET email= ' Jack@163.com ' WHERE username= ' Jack '
Tips
In order to ensure the security of the database, to avoid errors update the entire data table, if there is no update condition, the data object itself does not contain the primary key field, the Save method does not update the records of any database.
Therefore, to update the data using the Save () method, you must specify an update condition or include the primary key field in the updated data.
Examples of using primary keys:
Public Function Update () {header ("content-type:text/html; Charset=utf-8 "); $Dao = M ("User"); Data that needs 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 that needs to be updated contains the primary key, then thinkphp automatically updates the value of the primary key as a condition.
The above example has the same effect as the following:
Data that needs to be updated $data [' email '] = ' Jack@163.com ';
The updated condition $condition [' uid '] = 2; $result = $Dao->where ($condition)->save ($data);
If it is form data, you can also use the Create () method to make data objects 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 needs to be processed logically, it can be handled in the object or within the model, and the thinkphp form data is intelligently written to the Create method.
Note: To update data by creating a data object with the Create () method, the form must contain a hidden field with a primary key name in order to complete the save operation.
Third, thinkphp query data Select (FindAll) method
thinkphp query data mainly provides the following types of queries:
Select: Normal query, same as FindAll () method
Find: Get a record that meets the query criteria
Getby Dynamic query: A record that meets query criteria based on a field
GetField: Gets the value of a field or an indexed array of multiple fields
Interval query: Get the interval records that meet the query criteria
Statistical query: Obtain statistics that meet the query criteria
Locate query: Get one or more records that match the query criteria
Native SQL query: supports querying or performing operations with native SQL
Select ()
Select () is the most common query method used in thinkphp, and a two-dimensional array is obtained. FindAll () is an alias for the Select () method and it is recommended to use Select ().
Read operations
The following example reads all the data from the user table and displays:
Public function read () {$Dao = M ("User");//query data $list = $Dao->select ();//dump ($list);//dump () to see if the data has been read//template changed in the debug phase The volume assignment $this->assign ("list", $list);//Output Template $this->display ();}
Assuming that the above example corresponds to the class file 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 data from the User table just read. In the learning phase, you can also directly display the read data directly within the read () operation using the foreach syntax if you do not want to use a template. Here is the code snippet for the template, and we'll show the data we read 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 about thinkphp templates, see: thinkphp templates.
Field () queries the specified fields
The Select () method defaults to querying data for all fields, and if you are querying one or some of the fields, you need to use the filed () method.
Filed () is a method that belongs to the thinkphp coherent operation, as in the above example, querying only the user name and e-mail address, the Query method corresponds to the following changes:
$list = $Dao->field (' Username,email ')->select ();
Working with query criteria
Using thinkphp coherent operations makes it easy to use query criteria for data queries. Here are some examples of simple query conditions.
where () condition
...//construct query conditions $condition [' username '] = ' Admin '; Query data $list = $Dao->where ($condition)->select (); ......
The above query is the data of the username= ' Admin ' condition. For more detailed information about the thinkphp where condition, see the thinkphp where condition.
Order by sort
To sort data by using order by in a query:
...//query data $list = $Dao->order (' uid DESC ')->select (); ......
The example is that the data is queried by the order by UID DESC, and the parameter meaning in the order () method is exactly the same as the meaning in the SQL statement.
Limit limits
Number of records returned with limit qualification data in the query:
...//query data $list = $Dao->limit (' 4,5 ')->select (); ......
This example is to remove the 第5-10条 record, and the parameter meaning within the limit () method is exactly the same as the limit in the SQL statement.
Consistent operation
Each method in a data object is allowed to be written together in thinkphp, such as the following:
$list = $Dao->order (' uid DESC ')->limit (' 4,5 ')->select ();
This is a coherent operation, a more detailed introduction to the coherent operation, see thinkphp coherent operation.
Iv. thinkphp Deleting a data record Delete method
The Delete () method is used in thinkphp to remove data records from the database and also supports the use of coherent operations. The Delete () method performs a successful return operation that affects (deletes) the number of records.
Example:
Public Function del () {header ("content-type:text/html; Charset=utf-8 "); $Dao = M (" User "); Delete uid=5 data record $result = $Dao->where (' uid = 5 ')->delete (); if ($result!== false) {echo ' delete ', $result, ' bar data. ';} else{Echo ' Delete data failed! ';}}
The above example executes the SQL as:
DELETE from user WHERE uid = 5
The delete () method can be used to delete a single or multiple data, primarily depending on where () delete conditions. It is also possible to construct a more compliant deletion condition with other methods in the coherent operation, such as order () and limit ():
$Dao = M ("User"), $result = $Dao->where (' status=0 ')->order (' RegDate ASC ')->limit (' 5 ')->delete ();
The above example deletes 5 status=0 user records according to the user registration time in descending order.
It is hoped that this article is helpful to the PHP program design based on thinkphp framework.