Home Backend Development PHP Tutorial Some summary about adding, deleting, modifying and checking in ThinkPHP

Some summary about adding, deleting, modifying and checking in ThinkPHP

Jun 15, 2018 am 10:39 AM
user database

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);
Copy after login

Or use the data method to operate continuously

$User->data($data)->add();
Copy after login

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(); // 根据条件保存修改的数据
Copy after login

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();
Copy after login

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();
Copy after login

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');
Copy after login

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');
Copy after login

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); // 根据条件保存修改的数据
Copy after login

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对象
// 要修改的数据对象属性赋值
Copy after login

$data['id'] = 5;
$data['name'] = 'ThinkPHP';
$data['email'] = 'ThinkPHP@gmail.com';
$User->save($data); // 根据条件保存修改的数据
Copy after login

如果id是数据表的主键的话,系统自动会把主键的值作为更新条件来更新其他字段的值。

还有一种方法是通过create或者data方法创建要更新的数据对象,然后进行保存操作,这样save方法的参数可以不需要传入。

$User = M("User"); // 实例化User对象
// 要修改的数据对象属性赋值
$data['name'] = 'ThinkPHP';
$data['email'] = 'ThinkPHP@gmail.com';
$User->where('id=5')->data($data)->save(); // 根据条件保存修改的数据
Copy after login

使用create方法的例子:

$User = M("User"); // 实例化User对象
// 根据表单提交的POST数据创建数据对象
$User->create();
$User->save(); //根据条件保存要修改的数据
Copy after login

上面的情况,表单必须包含一个以主键为名称的隐藏域,才能完成保存操作。

如果只是更新个别字段的值,可以使用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'));
Copy after login

而对于统计字段(通常指的是数字类型)的更新,系统还提供了setIncsetDec方法:

$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
Copy after login

四、删除数据

在ThinkPHP使用delete方法删除数据库的记录。同样可以使用连贯操作进行删除操作。

$User = M("User"); // 实例化User对象
$User->where('id=5')->delete(); // 删除id为5的用户数据
$User->where('status=0')->delete(); // 删除所有状态为0的用户数据
Copy after login

delete方法可以用于删除单个或者多个数据,主要取决于删除条件,也就是where方法的参数,也可以用orderlimit方法来限制要删除的个数,例如:

// 删除所有状态为0的5个用户数据按照创建时间排序
$User->where('status=0')->order('create_time')->limit('5')->delete();
Copy after login

本文讲解了关于ThinkPHP的增、删、改、查 的一些总结,更多相关内容请关注php中文网。

相关推荐:

where方法的应用讲解

ThinkPHP 双重循环遍历输出 的相关内容

ThinkPHP5快速入门 方法的介绍

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!

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 does Go language implement the addition, deletion, modification and query operations of the database? How does Go language implement the addition, deletion, modification and query operations of the database? Mar 27, 2024 pm 09:39 PM

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Tips and practices for handling Chinese garbled characters in databases with PHP Tips and practices for handling Chinese garbled characters in databases with PHP Mar 27, 2024 pm 05:21 PM

PHP is a back-end programming language widely used in website development. It has powerful database operation functions and is often used to interact with databases such as MySQL. However, due to the complexity of Chinese character encoding, problems often arise when dealing with Chinese garbled characters in the database. This article will introduce the skills and practices of PHP in handling Chinese garbled characters in databases, including common causes of garbled characters, solutions and specific code examples. Common reasons for garbled characters are incorrect database character set settings: the correct character set needs to be selected when creating the database, such as utf8 or u

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

See all articles