


Some summary about adding, deleting, modifying and checking in ThinkPHP
Today I learned some operations on adding, deleting, modifying, and checking in ThinkPHP. I feel that the writing is quite clear. Let’s learn it together!
1. Creation operation
Use the add method in ThinkPHP to add data to the database.
The usage method is as follows:
$User = M("User"); // 实例化User对象 $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User->add($data);
Or use the data method to operate continuously
$User->data($data)->add();
If the data object has been created before add (for example, using the create or data method), the add method does not need to pass in data.
Example of using the create method:
$User = M("User"); // 实例化User对象 // 根据表单提交的POST数据创建数据对象 $User->create(); $User->add(); // 根据条件保存修改的数据
If your primary key is automatically growing type, and if the data is inserted successfully, the return value of the Add method is the latest inserted primary key value, which can be obtained directly.
2. Reading data
There are many ways to read data in ThinkPHP, usually divided into reading data and read datasets.
To read the data set, use the findall or select method (findall and select methods are equivalent):
$User = M("User"); // 实例化User对象 // 查找status值为1的用户数据以创建时间排序返回10条数据 $list = $User->where('status=1')->order('create_time')->limit(10)->select();
The return value of the select method is a two-dimensional array. If no results are found, an empty array is returned. Combined with the coherent operation method mentioned above, complex data queries can be completed. The most complex coherent method should be the use of the where method. Because this part involves a lot of content, we will use it in detail in the query language part on how to assemble query conditions. illustrate. The basic query does not involve the related query part for the time being, but uses the related model to perform data operations. Please refer to the related model part for this part.
Use the find method to read data:
The operation of reading data is actually similar to that of the data set. Select all the coherent operation methods available. They can also be used in the find method. The difference is that the find method will only return at most one record, so the limit method is invalid for the find query operation.
$User = M("User"); // 实例化User对象 // 查找status值为1name值为think的用户数据 $User->where('status=1 AND name="think" ')->find();
Even if there is more than one piece of data that meets the conditions, the find method will only return the first record.
If you want to read the value of a field, you can use the getField method, for example:
$User = M("User"); // 实例化User对象 // 获取ID为3的用户的昵称 $nickname = $User->where('id=3')->getField('nickname');
When there is only one field, always return a value.
If multiple fields are passed in, an associative array can be returned:
$User = M("User"); // 实例化User对象 // 获取所有用户的ID和昵称列表 $list = $User->getField('id,nickname');
The returned list is an array, the key name is the user's id, and the key value is the user's nickname.
3. Update data
Use the save method in ThinkPHP to update the database, and The use of coherent operations is also supported.
$User = M("User"); // 实例化User对象 // 要修改的数据对象属性赋值 $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User->where('id=5')->save($data); // 根据条件保存修改的数据
In order to ensure the security of the database and avoid errors, update the entire data table. If there are no update conditions, the data object itself will not contain For primary key fields, the save method will not update any database records.
Therefore the following code will not change any records in the database
$User->save($data);
除非使用下面的方式:
$User = M("User"); // 实例化User对象 // 要修改的数据对象属性赋值
$data['id'] = 5; $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User->save($data); // 根据条件保存修改的数据
如果id是数据表的主键的话,系统自动会把主键的值作为更新条件来更新其他字段的值。
还有一种方法是通过create或者data方法创建要更新的数据对象,然后进行保存操作,这样save方法的参数可以不需要传入。
$User = M("User"); // 实例化User对象 // 要修改的数据对象属性赋值 $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User->where('id=5')->data($data)->save(); // 根据条件保存修改的数据
使用create方法的例子:
$User = M("User"); // 实例化User对象 // 根据表单提交的POST数据创建数据对象 $User->create(); $User->save(); //根据条件保存要修改的数据
上面的情况,表单中必须包含一个以主键为名称的隐藏域,才能完成保存操作。
如果只是更新个别字段的值,可以使用setField方法:
$User = M("User"); // 实例化User对象 // 更改用户的name值 $User-> where('id=5')->setField('name','ThinkPHP'); setField方法支持同时更新多个字段,只需要传入数组即可,例如: $User = M("User"); // 实例化User对象 // 更改用户的name和email的值 $User-> where('id=5')->setField(array('name','email'),array('ThinkPHP','ThinkPHP@gmail.com'));
而对于统计字段(通常指的是数字类型)的更新,系统还提供了setInc和setDec方法:
$User = M("User"); // 实例化User对象 $User->setInc('score','id=5',3);// 用户的积分加3 $User->setInc('score','id=5'); // 用户的积分加1 $User->setDec('score','id=5',5);// 用户的积分减5 $User->setDec('score','id=5'); // 用户的积分减1
四、删除数据
在ThinkPHP中使用delete方法删除数据库中的记录。同样可以使用连贯操作进行删除操作。
$User = M("User"); // 实例化User对象 $User->where('id=5')->delete(); // 删除id为5的用户数据 $User->where('status=0')->delete(); // 删除所有状态为0的用户数据
delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数,也可以用order和limit方法来限制要删除的个数,例如:
// 删除所有状态为0的5个用户数据按照创建时间排序 $User->where('status=0')->order('create_time')->limit('5')->delete();
本文讲解了关于ThinkPHP的增、删、改、查 的一些总结,更多相关内容请关注php中文网。
相关推荐:
The above is the detailed content of Some summary about adding, deleting, modifying and checking in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
