Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of operating ThinkPHP data

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the ThinkPHP data operation methods, the article is very detailed, has a certain reference value, interested friends must read it!

The details are as follows:

1. ThinkPHP Insert add data

ThinkPHP's built-in add method is used to add data to the data table, which is equivalent to the INSERT INTO behavior in SQL.

The method of adding data add is the implementation of Create in CURD (Create,Update,Read,Delete / create, modify, read, delete). ThinkPHP supports writing data to data tables in a normal array and object-oriented manner.

Now take the example of manipulating user table data in the PHP MySQL Database tutorial (see: Insert Into data insertion usage Analysis of PHP+MySQL) as an example 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 / / build the written data array $data ["username"] = "Xiao Wang"; $data ["password"] = md5 ("123456"); $data ["email"] = 12345 163.compositional data ["regdate"] = time () / / write data if ($lastInsId = $Dao- > add ($data)) {echo "insert data id is: $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 new Model, called a shortcut method), and the parameter is the name of the table to be operated on.

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

Finally, the data is written to the library table with the add () method, and since you are using the M shortcut method, you need to pass the $data array into the add () method.

If the add () method successfully adds a data record, it returns the primary key of the new data record, which can be obtained directly.

The actual SQL for this example is:

INSERT INTO user (username,password,email,regdate) VALUES ('Xiao Wang', 'e10adc3949ba59abbe56e057f20f883e) 12345,163.com, 1283612673)

Tip: to run this example, please make sure that the relevant accounts and passwords of the database are correctly configured in the configuration file. For more information, please see "the method of combining ThinkPHP common configuration files with configuration files in their respective projects".

Object mode to add data

The above approach is to construct an array of data and then pass the data as parameters into the add method to write to the data table. ThinkPHP also supports writing data to the 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 = 12345mm 163.com; $Dao- > regdate = time (); / / write data if ($lastInsId = $Dao- > add ()) {echo "insert data id is: $lastInsId" } else {$this- > error ('data write error!') ;}}

Object mode except that the data is assigned as a data object, there is no need to pass parameters when calling the add method to write data.

2. Save method for updating data by ThinkPHP

Save ()

The save () method is used in ThinkPHP to update the database, and the use of coherent operations is also supported.

Example:

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

The SQL statement executed in the above example is:

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

Prompt

In order to ensure the security of the database and avoid errors to update the entire data table, if there are no update conditions and the data object itself does not contain primary key fields, the save method will not update any database records.

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

An example of using a primary key:

Public function update () {header ("Content-Type:text/html; charset=utf-8"); $Dao = M ("User"); / / 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 that needs 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:

/ / data to be updated $data ['email'] =' Jack@163.com'

/ / updated condition $condition ['uid'] = 2; $result = $Dao- > where ($condition)-> save ($data)

If it is 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 needs to be logically processed, it can be handled as an object in the action class or within the model. For more information, please refer to the "ThinkPHP form data Smart Writing create method".

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

Third, ThinkPHP query data select (findAll) method

ThinkPHP query data mainly provides the following types of queries:

Select: general query, same as findAll () method

Find: get a record that meets the query criteria

GetBy dynamic query: get a record that meets the query criteria according to a field

GetField: gets the value of a field or an indexed array of multiple fields

Interval query: obtain interval records that meet the query criteria

Statistical query: obtaining statistical data that meet the query criteria

Location query: get one or more records that meet the query criteria

Native SQL query: supports query or operation with native SQL

Select ()

Select () is the most common query method in ThinkPHP, and the result is a two-dimensional array. FindAll () is an alias for the select () method, and select () is recommended.

Read operation

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); / / use dump () to check whether the data has been read / / template variable assignment $this- > assign ("list", $list); / / output template $this- > display ();}

Assuming that the class file for 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 from the User table you just read. During the learning phase, if you don't want to use a template, you can use the foreach syntax to display the read data directly within the read () operation. The following is the corresponding code snippet for the template, and the data we read is displayed in a table:

ID username email registration time {$vo ['uid']} {$vo [' username']} {$vo ['email']} {$vo [' regdate'] | date='Y-m-d Hpuri email registration #}

To learn more about ThinkPHP templates, see "ThinkPHP templates".

Field () query the specified field

By default, the select () method queries the data of all fields, and if you want to query one or some fields, you need to use the filed () method.

Filed () is a method that belongs to the ThinkPHP coherent operation. For example, in the above example, if only the user name and e-mail address are queried, the query method will be changed to:

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

Use query conditions

Using ThinkPHP coherent operation, you can easily use query conditions for data queries. Here are some examples of simple query conditions.

Where () condition

…… / / construct query condition $condition ['username'] =' Admin'; / / query data $list = $Dao- > where ($condition)-> select ();...

The above query is the data of the username='Admin' condition. For more information about ThinkPHP where conditions, see "ThinkPHP Where conditions".

ORDER BY sorting

Use ORDER BY to sort the data in the query:

…… / / query data $list = $Dao- > order ('uid DESC')-> select ();...

This example is that the data is queried by ORDER BY uid DESC, and the meaning of the parameters in the order () method is exactly the same as that in the SQL statement.

LIMIT restriction

Use LIMIT in the query to limit the number of records returned by the data:

…… / / query data $list = $Dao- > limit ('4jing5')-> select ();...

This example is to take out records 5-10, and the meaning of the parameters in the limit () method is exactly the same as the LIMIT in the SQL statement.

Coherent operation

ThinkPHP allows you to write various methods in a data object together, such as:

$list = $Dao- > order ('uid DESC')-> limit (' 4jing5')-> select ()

This is the coherent operation. For a more detailed description of the coherent operation, see "ThinkPHP coherent operation".

4. ThinkPHP delete data record delete method

The delete () method is used in ThinkPHP to delete data records from the database, and the use of coherent operations is also supported. The successful execution of the delete () method returns the number of records affected (deleted) by the operation.

Example:

Public function del () {header ("Content-Type:text/html; charset=utf-8"); $Dao = M ("User"); / / Delete the data record of uid=5$ result = $Dao- > where ('uid=5')-> delete (); if ($result! = = false) {echo 'delete', $result,' entry. ;} else {echo 'failed to delete data!' ;}}

The SQL executed by the above example is:

DELETE FROM user WHERE uid = 5

The delete () method can be used to delete single or multiple data, depending on the where () deletion condition. In addition, you can also cooperate with other methods in the coherent operation, such as order (), limit (), etc., to construct deletion conditions that are more in line with the needs:

$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 the user registration time.

These are all the contents of the article "what are the ways to manipulate ThinkPHP data?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report