Home Backend Development PHP Tutorial Curd operation of ThinkPHP_PHP tutorial

Curd operation of ThinkPHP_PHP tutorial

Jul 14, 2016 am 10:10 AM
thinkphp and accomplish right supply operate data method flexible of

ThinkPHP provides flexible and convenient data operation methods. It not only implements the four basic operations of database operations (CURD): create, read, update and delete, but also has many practical data operation methods built-in. Provides the best experience in ActiveRecords mode.


Create new record


PHP code


1. $User->find(2);


2. $User->delete(); // Delete the found record


3. $User->delete('5,6'); // Delete data with primary keys 5 and 6


4. $User->deleteAll(); // Delete all the queried data


PHP code


1. // Instantiate a User model object


2. 


3. $User = new UserModel();


4. // Then assign a value to the data object


5. $User->name = 'ThinkPHP';


6. $User->email = 'ThinkPHP@gmail.com';


7. // Then you can save the new User object


8. $User->add();


9. // If you need to lock the data when instantiating the model object, you can use


10.            $data['name'] = 'ThinkPHP'; 


11.          $data['email'] = 'ThinkPHP@gmail.com';


"

13. $User->add();

14.                   // Or directly pass in the new data to be created in the add method

15.           $data['name'] = 'ThinkPHP'; 

16.          $data['email'] = 'ThinkPHP@gmail.com';

17. $User = new UserModel();

18. $User->add($data);

19.                                           

20.                                            



Under normal circumstances, data objects in applications are unlikely to be written through manual assignment, but there is a data object creation process. ThinkPHP provides a create method to create data objects, and then perform other adding or editing operations.


PHP code


1. $User = D("User");


2. $User->create(); // Create User data object, which is created by default through the data submitted by the form


3. $User->add(); // Add data submitted by the form


The Create method supports creating data objects in other ways, for example, from other data objects, or arrays, etc.


PHP code


1. $data['name'] = 'ThinkPHP';


2. $data['email'] = 'ThinkPHP@gmail.com';


3. $User->create($data);


4. // Create a new Member data object from the User data object


5. $Member = D("Member");


6. $Member->create($User);



Support adding multiple records


PHP code


1. $User = new UserModel();


2. $data[0]['name'] = 'ThinkPHP';


3. $data[0]['email'] = 'ThinkPHP@gmail.com';


4. $data[1]['name'] = 'Fleeting Years';


5. $data[1]['email'] = 'liu21st@gmail.com';


6. $User->addAll($data);


Under the MySql database, one SQL statement will be automatically used to insert multiple data.


Query records


I think reading database records is the most interesting thing in database operations. Anyone who has written a text database knows that it is not difficult to save and delete data (it is nothing more than a matter of standardization and efficiency). The difficulty is that it can be done through various way to find the data you need. Through various efforts, ThinkPHP makes database query operations easy and makes ThinkPHP rich in content.


ThinkPHP has a very clear convention, that is, the methods of single data query and multiple data query are separate, or you may think that sometimes you don’t know whether the data you want to query is single or multiple, but one thing is clear, Do you need to return a piece of data or do you want a data set to be returned? Because the operation methods for the two types of returned data are completely different, no matter which method is returned, we can operate directly in the model object, and of course it can also be passed as data to the variables you need.


Let’s take the simplest example first. If we want to query a user record whose primary key is 8, we can use the following methods:


PHP code


1. $User->find(8);


This is the most intuitive as a query language. If the query is successful, the query results are directly stored in the current data object. We can extract them before the next query operation, such as obtaining the query result data:


PHP code


1. $name = $User->name;


2. $email = $User->email;


Traverse the queried data object attributes


PHP code


1. foreach ($User as $key=>$val){


2. echo($key.':'.$val);


3. }


// Or perform related data changes and save operations


You can also use variables to save them for use at any time.


PHP code


1. $user = $User->find(8);


For the above query conditions, we can also use getById to complete the same query


PHP code


1. $User->getById(8);


It should be noted that for the find method, even if the query result has multiple records, only the first record that meets the conditions will be returned. If you want to return all records that meet the requirements, please use the findAll method.


PHP code


1. // Query the record set whose primary key is 1, 3, 8


2. $User->findAll('1,3,8');


3. // Traverse the data list


4. foreach ($User as $vo){


5. dump($vo->name);


6. }  


For more query operations, please refer to the following chapters.


                           


Update record


After understanding the query record, the update operation is very simple.


// You can also use the following method to update


PHP code


1. $User->find(1); // Find data with primary key 1


2. $User->name = 'TOPThink'; // Modify data object


3. $User->save(); // Save the current data object


4. $User->score = '(score+1)'; // Add 1 to the user's points


5. $User->save();


If you do not use data objects to save, you can pass in the data and conditions to be saved


PHP code


1. $data['id'] = 1;


2. $data['name'] = 'TopThink';


3. $User->save($data);


In addition to the save method, you can also use the setField method to update the value of a specific field, for example:


PHP code


1. $User->setField('name','TopThink','id=1');


Operations on fields can also be supported


PHP code


1. $User->setField('score','(score+1)','id=1');


2. // Or change it to the following


3. $User->setInc('score','id=1');


Delete record


If your primary key is an automatic growth type, you can create new data without passing in the value of the primary key. 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.


echo $user->getLastSql();

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477477.htmlTechArticleThinkPHP provides flexible and convenient data operation methods, not only realizing the four basic operations of database operations (CURD ): Implementation of creation, reading, updating and deletion, and many built-in...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

See all articles