


thinkphp implements basic addition, deletion, modification and query
ThinkPHP provides flexible and convenient data operation methods, which not only realizes the four basic operations of database operations (CURD): The implementation of creation, reading, updating and deletion also has many practical data operation methods built in. Next, we will learn these basic operation methods together, and prepare an example for everyone to deepen their understanding at the end.
New data
// 实例化一个User模型对象 $User = new UserModel(); // 然后给数据对象赋值 $User->name = 'ThinkPHP'; $User->email = 'ThinkPHP@gmail.com'; // 然后就可以保存新建的User对象了 $User->add(); //如果需要锁实例化模型对象的时候传入数据,可以使用 $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User = new UserModel($data); $User->add(); // 或者直接在add方法传入要新建的数据 $data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User = new UserModel(); $User->add($data);
Under normal circumstances, the data objects in the application are unlikely to be written through manual assignment, but there is a data object creation process. ThinkPHP provides a create method to create a data object, and then perform other adding or editing operations.
$User = D("User"); $User->create(); // 创建User数据对象,默认通过表单提交的数据进行创建 $User->add(); // 新增表单提交的数据
Create Method supports creating data objects from other ways, for example, from other data objects, or arrays, etc.
$data['name'] = 'ThinkPHP'; $data['email'] = 'ThinkPHP@gmail.com'; $User->create($data); // 从User数据对象创建新的Member数据对象 $Member = D("Member"); $Member->create($User);
支持新增多条记录
$User = new UserModel(); $data[0]['name'] = 'ThinkPHP'; $data[0]['email'] = 'ThinkPHP@gmail.com'; $data[1]['name'] = '流年'; $data[1]['email'] = 'liu21st@gmail.com'; $User->addAll($data);
Under the MySql database, a SQL statement will be automatically used to insert multiple data.
Query records
##Read the database I think the record 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 searched in various ways. required data. ThinkPHPThrough various efforts, database query operations have become easy, and ThinkPHP has become rich in content. ThinkPHP
There is a very clear agreement that the methods of single data query and multiple data query are separate, or you may think that sometimes you don’t know what to query. Whether the data is single or multiple, but one thing is clear, do you need to return one data or do you want to return a data set. Because the two types of return data are operated in completely different ways, 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 some of the methods below:
$User->find(8);
这个作为查询语言来说是最为直观的,如果查询成功,查询的结果直接保存在当前的数据对象中,在进行下一次查询操作之前,我们都可以提取,例如获取查询的结果数据:
$name = $User->name; $email = $User->email;
遍历查询到的数据对象属性
foreach ($User as $key=>$val){ echo($key.':'.$val); }
// 或者进行相关的数据更改和保存操作
也可以用变量保存下来以便随时使用。
$user = $User->find(8);
对于上面的查询条件,我们还可以使用getById来完成相同的查询
$User->getById(8);
需要注意的是,对于find方法来说,即使查询结果有多条记录,也只会返回符合条件的第一条记录,如果要返回符合要求的所有记录,请使用findAll方法。
// 查询主键为1、3、8的记录集 $User->findAll('1,3,8'); // 遍历数据列表 foreach ($User as $vo){dump($vo->name); }
更新记录
了解了查询记录后,更新操作就显得非常简单了。
// 还可以使用下面的方式更新 $User->find(1); // 查找主键为1的数据 $User->name = 'TOPThink'; // 修改数据对象 $User->save(); // 保存当前数据对象 $User->score = '(score+1)'; // 对用户的积分加1 $User->save();
如果不是使用数据对象的方式来保存,可以传入要保存的数据和条件
$data['id'] = 1; $data['name'] = 'TopThink'; $User->save($data);
除了save方法外,你还可以使用setField方法来更新特定字段的值,例如:
$User->setField('name','TopThink','id=1');
同样可以支持对字段的操作
$User->setField('score','(score+1)','id=1'); // 或者改成下面的 $User->setInc('score','id=1');
删除记录
如果你的主键是自动增长类型,不需要传入主键的值就可以新建数据,并且如果插入数据成功的话,Add方法的返回值就是最新插入的主键值,可以直接获取。
$User->find(2); $User->delete(); // 删除查找到的记录 $User->delete('5,6'); // 删除主键为5、6的数据 $User->deleteAll(); // 删除查询出来的所有数据
看完上面的代码,我们就来写个实战的例子加深下。
数据显示页面:MainController.class.php中的方法
<?php namespace Home\Controller; use Think\Controller; class MainController extends Controller { //例题:数据的增删改 //显示所有数据: function ShowInfo() { $model=D("Info"); $attr=$model->field("info.code as infocode,info.name as infoname,info.sex,nation.name as nationname,info.birthday")->join("nation on info.nation=nation.code")->select(); $this->assign("shuju",$attr); $this->display(); } //删除数据: function ShanChu($code) { $model=D("Info"); $r=$model->delete($code); if($r) { $this->success("删除成功",U("ShowInfo")); } else { $this->error("删除失败"); } } //添加数据: function TianJia() { if(empty($_POST)) { $model=D("Nation"); $attr=$model->select(); $this->assign("shuju",$attr); $this->display(); } else { $model=D("Info"); $model->create();//自动收集表单数据入库 $model->Sex=$_POST["Sex"]=="男"?true:false; $r=$model->add(); if($r) { $this->success("添加成功!","Tianjia",3); } else { $this->error("添加失败!","Tianjia",3); } } } //修改数据: function XiuGai($code) { $model=D("info"); $modeln=D("nation"); if(empty($_POST)) { $attr=$model->find($code); $attrn=$modeln->select(); $this->assign("shuju",$attr); $this->assign("shujun",$attrn); $this->display(); } else { $model->create(); $model->Sex=$_POST["Sex"]=="男"?true:false; $r=$model->save(); if($r) { $this->success("修改成功",U("Showinfo")); } else { $this->error("修改失败!"); } } } }
模板的数据显示:ShowInfo.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>主页面</title> </head> <body> <h2 id="主页面">主页面</h2> <table width="70%" cellpadding="0" cellspacing="0" border="1"> <tr> <td>代号</td> <td>姓名</td> <td>性别</td> <td>民族</td> <td>生日</td> <td>操作</td> </tr> <foreach name="shuju" item="v"> <tr> <td><{$v.infocode}></td> <td><{$v.infoname}></td> <td><{$v["sex"]?"男":"女"}></td> <td><{$v.nationname}></td> <td><{$v.birthday}></td> <td><a href="__CONTROLLER__/XiuGai/code/<{$v.infocode}>">修改</a> <a href="__CONTROLLER__/ShanChu/code/<{$v.infocode}>">删除</a></td> </tr> </foreach> </table> <a href="__CONTROLLER__/TianJia">添加数据</a> </body> </html>
添加数据模板显示:Tianjia.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>添加数据</title> </head> <body> <h1 id="添加数据">添加数据</h1> <form action="/index.php/Article/edit" method="post"> <p>代号:<input type="text" name="Code" /></p> <p>姓名:<input type="text" name="Name" /></p> <p>性别:<input type="radio" name="Sex" value="男" />男 <input type="radio" name="Sex" value="女" />女 </p> <p>民族: <select name="Nation"> <foreach name="shuju" item="v"> <option value="<{$v.code}>"><{$v.name}></option> </foreach> </select> </p> <p>生日:<input type="text" name="Birthday" /></p> <input type="submit" value="添加" /> </form> <a href="__CONTROLLER__/ShowInfo">返回主页面</a> </body> </html>
修改模板数据显示:Xiugai.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>修改数据</title> </head> <body> <h1 id="修改数据">修改数据</h1> <form action="/index.php/Article/edit/code/<{$shuju.code}>" method="post"> <input type="hidden" name="Code" value="<{$shuju.code}>" /> <p>姓名:<input type="text" name="Name" value="<{$shuju.name}>"/></p> <p>性别:<input type="radio" name="Sex" value="男" <{$shuju["sex"]?"checked='checked'":""}>/>男 <input type="radio" name="Sex" value="女" <{$shuju["sex"]?"":"checked='checked'"}> />女 </p> <p>民族: <select name="Nation"> <foreach name="shujun" item="v"> <if condition="$shuju['nation']==$v['code']"> <option selected="selected" value="<{$v.code}>"><{$v.name}></option> <else/> <option value="<{$v.code}>"><{$v.name}></option> </if> </foreach> </select> </p> <p>生日:<input type="text" name="Birthday" value="<{$shuju.birthday}>" /></p> <input type="submit" value="修改" /> </form> <a href="__CONTROLLER__/ShowInfo">返回主页面</a> </body> </html>
主页面:
添加数据
Modify data:
##Delete data :
The above are the basic methods and examples of Thinkphp addition, deletion, modification and query brought to you by 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



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.

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.

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

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.

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.
