thinkphp Data Operation Method Summary _php Example

Source: Internet
Author: User
Tags md5 php mysql

This paper summarizes the operation method of thinkphp data. Share to everyone for your reference. Specifically as follows:

One, thinkphp Insert add data

The thinkphp built-in Add method is used to add data to a datasheet, 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 a datasheet in a normal array and object-oriented way.

Take the example of manipulating user table data in the PHP MySQL database tutorial (see also: Php+mysql inserts into data insertion usage analysis) to demonstrate how to implement data add operations to a datasheet in thinkphp.

Example:

In the Indexaction controller (lib/action/indexaction.class.php), add the Insert () Action:

Public Function Insert ()
{
header (content-type:text/html; Charset=utf-8 ");
 $Dao = M ("User"); Instantiate the Model class//build the written data array
 $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

Grammar interpretation

M ("User") is used to efficiently instantiate a data model (M is shorthand for new Model, called a shortcut method), and the parameter is the name of the table to be manipulated.

Next, build the array $data to save the data.

Finally, use the Add () method to write the data into the storage table, because the use of the M shortcut method, you need to pass $data array into the Add () method.

The Add () method returns the primary key of the new data record if the data record is added successfully, which can be obtained directly.
The example actually runs in SQL is:

INSERT into User
(username,password,email,regdate)
 VALUES
(' Xiao Wang ', ' e10adc3949ba59abbe56e057f20f883e ', ' 12345@163.com ', 1283612673)

Tip: To run this example, make sure that you have correctly configured the relevant account password for the database in the configuration file, and so on, see the thinkphp Common configuration file and the method of the configuration file in the respective project.

Object method to add data

The above approach is to construct the array of data and then pass the data into the Add method as a parameter to write to the datasheet. Thinkphp also supports writing data to a data table as an object, changing the above code 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 Way In addition to data as data object assignment, the Add method is invoked to write data without the need to pass parameters.

Second, thinkphp Update data Save method

Save ()

The Save () method is used in thinkphp to update the database and also supports the use of consecutive operations.
Example:

Public Function Update () {
header (content-type:text/html; Charset=utf-8 ");
$Dao = M ("User"); Need to update the data
 $data [' email '] = ' Jack@163.com ';
Updated condition $condition [' username '] = ' Jack ';
 $result = $Dao->where ($condition)->save ($data);
Alternatively: $resul t= $Dao->where ($condition)->data ($data)->save ();
if ($result!== false) {echo ' Data update succeeded! ';
}
else{
echo ' Data update failed! ';
 }
}

The SQL statement executed in the example above is:

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

Tips

The Save method does not update records for any database in order to ensure the security of the database and to prevent errors from updating the entire datasheet, and if there are no update conditions and the data object itself does not contain a primary key field.

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

Examples of using primary keys:

Public Function Update () {
 header (content-type:text/html; Charset=utf-8 ");
 $Dao = M ("User"); The data that needs to be updated
 $data [' email '] = ' Jack@163.com '; $data [' uid '] = 2;
 $result = $Dao->save ($data);
if ($result!== false)
{
echo ' data update succeeded! ';
 } else{
echo ' Data update failed! ';
 }
}

If the data that needs to be updated contains a primary key, then thinkphp automatically updates the value of the primary key as a condition.

The example above has the same effect as the following:

Need to update the data $data [' email '] = ' Jack@163.com ';
The updated condition $condition [' uid '] = 2; $result = $Dao->where ($condition)->save ($data);
If you are 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 update succeeded! ';
} else{
echo ' Data update failed! ';
 } }
else{
$this->error ($Form->geterror ());
 }

If the updated data needs to be done logically, the action class can be handled in an object or in a model, referring to the thinkphp form data Intelligent Write create method.

Note: the Create () method creates a data object to update the data, and the form must contain a hidden field with the primary key name to complete the save operation.

Three, thinkphp query data Select (FindAll) method

thinkphp query data mainly provides the following types of queries:
Select: Common Query, same findall () method
Find: Get a record that matches the criteria
Getby Dynamic query: A record that matches the query criteria according to 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 conditions
Statistical query: Obtain statistics that meet the query criteria
Locate query: Get one or more records that meet the query criteria
Native SQL query: supports querying or performing operations in native SQL

Select ()

Select () is the most common common query method in thinkphp, and a two-dimensional array is obtained. FindAll () is an alias for the Select () method, and it is recommended that you use Select ().

Read operations

The following example reads all the data from the user table and displays it:

Public function read ()
{
$Dao = M ("User");//query data
$list = $Dao->select ();
Dump ($list);
Dump () allows you to see whether the data has been read
//template variable assigned $this->assign ("list", $list) during the debug phase;
Output template $this->display ();
}

Assuming that the above example corresponds to the class file as 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 that you just read. In the learning phase, if you do not want to use a template, you can directly display the read data directly in the read () operation using the foreach syntax. Here is the corresponding code snippet for the template, and we will read the data in a table:

<table border= "1" >
 <tr>
<th width= "10%" >ID</th>
 <th width= "30%" > User name < /th>
 <th width= "30%" > Email </th>
<th> registration time </th>
 </tr>
<volist Name= "list" id= "Vo" >
<tr>
<td align= "center" >{$vo [' uid ']}</td>
 <td>{$vo [' Username ']} </td>
<td>{$vo [' email ']}</td>
 <td>{$vo [' regdate ']|date= ' y-m-d h:i ', ###}</ td>
 </tr>
</volist>
</table>

To learn more about thinkphp templates, see the "thinkphp template."

Field () query specifies fields

The Select () method defaults to querying the data for all fields, and if you want to query for one or more fields, you need to use the filed () method.

Filed () is a method that is part of a thinkphp coherent operation, as in the example above, querying only the username and e-mail address, the Query method corresponds to the following change:

$list = $Dao->field (' Username,email ')->select ();

Using query criteria

Using thinkphp coherent operation makes it convenient 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 Username= ' Admin ' The data of this condition. For more detailed information about thinkphp where conditions, 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 (); ......
This example is where 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 limit

Use LIMIT in a query to qualify the number of records returned by the data:
...//query data $list = $Dao->limit (' 4,5 ')->select (); ......
This example is the 第5-10条 record is removed, the limit () method in the parameter meaning in the SQL statement is exactly the same as the limit.

Coherent operation

Thinkphp allows you to write each method in a data object together, such as:
$list = $Dao->order (' uid DESC ')->limit (' 4,5 ')->select ();
This is a coherent operation, a more detailed description of the coherent operation, see "thinkphp coherent operation".

iv. thinkphp Delete data record Delete method

The Delete () method is used in thinkphp to delete data records in the database and also supports the use of consecutive operations. The Delete () method performs a successful return of the number of records affected (deleted) by the operation.

Example:

Public Function del () {
 header ("content-type:text/html; Charset=utf-8 ");
$Dao = M ("User"); Deletes the uid=5 data record
 $result = $Dao->where (' uid = 5 ')->delete ();
 if ($result!== false) {
echo ' deletes ', $result, ' piece of data. ';
} else{
 Echo ' Delete data failed! ';
}
}

The above example executes SQL as:

DELETE from user WHERE uid = 5

The delete () method can be used to delete single or multiple data, depending largely on where () deletion criteria. In addition, it is possible to construct a more suitable deletion condition with other methods such as order (), limit () and so on in a coherent operation:

$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 descending order of user registration time.

I hope this article will help you with the PHP program design based on thinkphp framework.

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.