thinkphp5.0 study notes database operation
ThinkPHP has a built-in abstract database access layer that encapsulates different database operations. We only need to use the public Db class to operate without writing different codes and underlying implementations for different databases. The Db class will Automatically call the corresponding database driver for processing. Using PDO method, it currently includes support for Mysql, SqlServer, PgSQL, Sqlite and other databases.
1. Basic use
After configuring the database connection information, we can directly use the database to run native SQL operations, supportquery
(query operation) and execute
(write operation) methods, and support parameter binding.
public function read() {$sql = Db::query('select * from news'); dump($sql); }
The output is:
execute method:
public function read() {$sql = Db::execute('insert into news (nid, rid) values (11, 11)');; dump($sql); }
Output:
Database added successfully!
also supports named placeholder bindings, for example:
public function read() {$sql = Db::query('select * from news where nid=:nid',['nid'=>1]); dump($sql); }
Output:
execute method:
public function read() {$sql = Db::execute('insert into news (nid, rid) values (:nid, :rid)',['nid'=>18,'rid'=>'121']); dump($sql); }
Output :
Database added successfully!
Multiple database connections can be used :
2. Query constructor
You can tell by the name, it’s very pretentious..
Let’s look at the basic query;
Query a data:
// table方法必须指定完整的数据表名$sql =Db::table('news')->where('nid',1)->find(); dump($sql);
find = Query one item; and the query result does not exist, return null
Output:
Db::table('think_user')->where('status',1)->select();
This query statement is the same as the above, but the select method query result does not exist and an empty array is returned.
Well, this thing is called a query data set, that’s right!
By default, the find and select methods return arrays.
If you want to query the value of a certain field, what should you do?
public function read() {// 返回某个字段的值$sql =Db::table('news')->where('nid',18)->value('rid'); dump($sql); }
这样看输出,我求rid的值:
如果你需要处理成千上百条数据库记录,可以考虑使用chunk方法,该方法一次获取结果集的一小块,然后填充每一小块数据到要处理的闭包,该方法在编写处理大量数据库记录的时候非常有用。
public function read() {$sql =Db::table('news')->chunk(1,function($user){foreach($user as $u) { dump($u); } }); }
这个样子 就可以一条一条都给遍历出来了!
是“一条一条·”,嘿!
3.添加数据跟删除数据
使用 Db
类的 insert
方法向数据库提交数据
public function read() {$data = ['ntitle' => '123', 'rid' => '456'];$sql = Db::table('news')->insert($data); dump($sql); }
添加成功后insert 方法返回添加成功的条数,insert 正常情况返回 1
添加数据后如果需要返回新增数据的自增主键,可以使用getLastInsID
方法:
public function read() {$data = ['ntitle' => '123', 'rid' => '345'];$sql = Db::table('news')->insert($data);$userId = Db::name('news')->getLastInsID('nid'); dump($userId); dump($sql); }
看输出:
主键字段22!
添加多条数据:
添加多条数据直接向 Db 类的 insertAll 方法传入需要添加的数据即可;
public function read() {$data = [ ['ntitle' =>'gaga','rid' => '12'],['ntitle' =>'gaaaga','rid' => '123'] ];$sql = Db::table('news')->insertAll($data); dump($sql); }
这样的话,返回的应该是两条2
删除数据:
根据主键来删除
public function read() {// 根据主键 来删$sql = Db::table('news')->delete(1);//多删 //$sql = Db::table('news')->delete(1,2,3);dump($sql); }
执行成功返回影响行数;
还有一种是根据条件来删除的
public function read() {// 根据条件 来删$sql = Db::table('news')->where('nid',18)->delete();//多删 //$sql = Db::table('news')->where('nid','<',1)->delete();dump($sql); }
执行成功也是返回影响行数;
4.查询方法:
where方法:
可以使用where
方法进行AND
条件查询:
public function read() {$sql = Db::table('news')->where('nid',20)->where('ntitle',123)->find(); dump($sql); }
whereOr方法:
使用whereOr
方法进行OR
查询:
public function read() {$sql = Db::table('news')->where('nid',20)->whereOr('ntitle','like','%123%')->find(); dump($sql); }
混合查询:
where方法和whereOr方法在复杂的查询条件中经常需要配合一起混合使用
public function read() {$sql = Db::table('news')->where(function($query){$query->where('nid',21)->where('nid',22); })->whereOr(function($query) {$query->where('ntitle','123')->whereOr('ntitle','123'); })->select(); dump($sql); }
输出的是:
看一下生成的代码:
SELECT * FROM `news` WHERE ( `nid` = 1 OR `nid` = 2 ) OR ( `ntitle` LIKE '123' OR `ntitle` LIKE '123' )
第一个查询方法用where或者whereOr是没有区别的。
查询接五
The above is the detailed content of thinkphp5.0 study notes database operation. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.
