Table of Contents
Basic usage
Query constructor
Assistant function
Update data
Delete data
Conditional query method
Query expression
Home PHP Framework ThinkPHP Let's talk about Thinkphp 5.0's operation of database (key code)

Let's talk about Thinkphp 5.0's operation of database (key code)

Sep 23, 2022 pm 07:28 PM
php thinkphp

A standard website must be inseparable from database operations. In this set of courses, I will work with you to uncover the mystery of ThinkPHP5 data operations, and happily use ThinkPHP5 to operate the database with you, making database operations more changeable. Pleasure.

Let's talk about Thinkphp 5.0's operation of database (key code)

Basic usage

Query operation

Db::query('select * from think_user where id=?',[8]);

Write operation

Db::execute('insert into think_user (id, name) values (?, ?)',[8,'thinkphp']);

Query constructor

Query data

find returns a record, and the result returned is a one-dimensional array. If the result does not exist, NULL is returned.

Db::table('think_user')->where('id',1)->find();

select returns all records, and the result returned is a two-dimensional array. If the result does not exist, NULL is returned. Exists, returns an empty array

Db::table('think_user')->where('status',1)->select();

Assistant function

The system provides a db assistant function for more convenient query:

db('user')->where('id',1)->find();
db('user')->where('status',1)->select();

Note: Using the db assistant function will reconnect to the database every time by default, while using the Db::name or Db::table method is a singleton. If the db function needs to use the same link, you can pass in the third parameter, for example

db('user',[],false)->where('id',1)->find();
db('user',[],false)->where('status',1)->select();

Add data

Use Db The insert method of the class submits data to the database

$data = ['foo' => 'bar', 'bar' => 'foo'];
Db::table('think_user')->insert($data);

Add multiple pieces of data

Add multiple pieces of data and pass it directly to the insertAll method of the Db class The data that needs to be added can be

$data = [    ['foo' => 'bar', 'bar' => 'foo'],
    ['foo' => 'bar1', 'bar' => 'foo1'],
    ['foo' => 'bar2', 'bar' => 'foo2']
];
Db::name('user')->insertAll($data);

insertAll method adds data successfully and returns the number of successfully added items

Assistant function

// 添加单条数据
db('user')->insert($data);

// 添加多条数据
db('user')->insertAll($list);

Update data

update method returns the number of affected data, no data is modified and returns 0

Db::table('think_user')->where('id', 1)->update(['name' => 'thinkphp']);

Update the value of a certain field: setField method returns the number of affected data, no data is modified The data field returns 0

Db::table('think_user')->where('id',1)->setField('name', 'thinkphp');
自增或自减一个字段的值
// score 字段加 1
Db::table('think_user')->where('id', 1)->setInc('score');
// score 字段加 5
Db::table('think_user')->where('id', 1)->setInc('score', 5);
// score 字段减 1
Db::table('think_user')->where('id', 1)->setDec('score');
// score 字段减 5
Db::table('think_user')->where('id', 1)->setDec('score', 5);

Delayed update

Db::table('think_user')->where('id', 1)->setInc('score', 1, 10);

Delete data

// 根据主键删除
Db::table('think_user')->delete(1);
Db::table('think_user')->delete([1,2,3]);

// 条件删除    
Db::table('think_user')->where('id',1)->delete();
Db::table('think_user')->where('id','<&#39;,10)->delete();

Conditional query method

where

You can use the where method to query AND conditions:

Db::table('think_user')
    ->where('name','like','%thinkphp')
    ->where('status',1)
    ->find();

whereOr method

Db::table('think_user')
    ->where('name','like','%thinkphp')
    ->whereOr('title','like','%thinkphp')
    ->find();

Mixed query

where method and whereOr method often need to be mixed together in complex query conditions. Here is an example:

$result = Db::table('think_user')->where(function ($query) {
    $query->where('id', 1)->whereor('id', 2);
})->whereOr(function ($query) {
    $query->where('name', 'like', 'think')->whereOr('name', 'like', 'thinkphp');
})->select();

Query expression

Query expression supports most SQL query syntax and is also the essence of ThinkPHP query language. The usage format of query expression is:

where('字段名','表达式','查询条件');
whereOr('字段名','表达式','查询条件');
表达式 含义
EQ、= 等于(=)
NEQ、<> 不等于(<>)
GT、> 大于(>)
EGT、>= 大于等于(>=)
LT、< 小于(<)
ELT、<= 小于等于(<=)
LIKE 模糊查询
[NOT] BETWEEN (不在)区间查询
[NOT] IN (不在)IN 查询
[NOT] NULL 查询字段是否(不)是NULL
[NOT] EXISTS EXISTS查询
EXP 表达式查询,支持SQL语法
> time 时间比较
< time 时间比较
between time 时间比较
notbetween time 时间比较

[Related tutorial recommendations: thinkphp framework]

The above is the detailed content of Let's talk about Thinkphp 5.0's operation of database (key code). 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1582
276
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Building Immutable Objects in PHP with Readonly Properties Building Immutable Objects in PHP with Readonly Properties Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

edge pdf viewer not working edge pdf viewer not working Aug 07, 2025 pm 04:36 PM

TestthePDFinanotherapptodetermineiftheissueiswiththefileorEdge.2.Enablethebuilt-inPDFviewerbyturningoff"AlwaysopenPDFfilesexternally"and"DownloadPDFfiles"inEdgesettings.3.Clearbrowsingdataincludingcookiesandcachedfilestoresolveren

Java Performance Optimization and Profiling Techniques Java Performance Optimization and Profiling Techniques Jul 31, 2025 am 03:58 AM

Use performance analysis tools to locate bottlenecks, use VisualVM or JProfiler in the development and testing stage, and give priority to Async-Profiler in the production environment; 2. Reduce object creation, reuse objects, use StringBuilder to replace string splicing, and select appropriate GC strategies; 3. Optimize collection usage, select and preset initial capacity according to the scene; 4. Optimize concurrency, use concurrent collections, reduce lock granularity, and set thread pool reasonably; 5. Tune JVM parameters, set reasonable heap size and low-latency garbage collector and enable GC logs; 6. Avoid reflection at the code level, replace wrapper classes with basic types, delay initialization, and use final and static; 7. Continuous performance testing and monitoring, combined with JMH

Yii Developer: Mastering the Essential Technical Skills Yii Developer: Mastering the Essential Technical Skills Aug 04, 2025 pm 04:54 PM

To become a master of Yii, you need to master the following skills: 1) Understand Yii's MVC architecture, 2) Proficient in using ActiveRecordORM, 3) Effectively utilize Gii code generation tools, 4) Master Yii's verification rules, 5) Optimize database query performance, 6) Continuously pay attention to Yii ecosystem and community resources. Through the learning and practice of these skills, the development capabilities under the Yii framework can be comprehensively improved.

Using PHP for Data Scraping and Web Automation Using PHP for Data Scraping and Web Automation Aug 01, 2025 am 07:45 AM

UseGuzzleforrobustHTTPrequestswithheadersandtimeouts.2.ParseHTMLefficientlywithSymfonyDomCrawlerusingCSSselectors.3.HandleJavaScript-heavysitesbyintegratingPuppeteerviaPHPexec()torenderpages.4.Respectrobots.txt,adddelays,rotateuseragents,anduseproxie

VS Code shortcut to focus on explorer panel VS Code shortcut to focus on explorer panel Aug 08, 2025 am 04:00 AM

In VSCode, you can quickly switch the panel and editing area through shortcut keys. To jump to the left Explorer panel, use Ctrl Shift E (Windows/Linux) or Cmd Shift E (Mac); return to the editing area to use Ctrl ` or Esc or Ctrl 1~9. Compared to mouse operation, keyboard shortcuts are more efficient and do not interrupt the encoding rhythm. Other tips include: Ctrl KCtrl E Focus Search Box, F2 Rename File, Delete File, Enter Open File, Arrow Key Expand/Collapse Folder.

See all articles