search
HomeBackend DevelopmentPHP TutorialThinkPHP的CURD步骤及查询方法一览

ThinkPHP的CURD方法及查询方法一览

所谓CURD。即对数据库操作的四个基本操作(CURD):C:create(创建)、U:update(更新)、R:read(读取)和D:detele(删除)。
在ThinkPHP中,并不是一定以这几个名字的方法,这里列出常见的:select,find,findAll,save,create等方法:

D读取:
select->()查询数据集,和findAll->()相同。例如:
$User->where(‘status=1′)->order(‘create_time’)->limit(10)->select();
注意:在连贯操作中除了select方法必须放到最后一个外,其他的连贯操作的方法调用顺序没有先后,例如,下面的代码和上面的等效:
$User->order(‘create_time’)->where(‘status=1′)->limit(10)->select();

如果丌习惯使用连贯操作癿话,新版迓支持直接使用参数迕行查诟癿方式。例如上面癿代码可以改
写为: 
$User->select(array('order'=>'create_time', 'where'=>'status=1', 'limit'=>'10')); 



find->()方法,和以上两种方法类似。区别在只返回一条数据。可以和getField->()获取一条记录的某个字段值一起用。

select和findall效果一样,返回的是一个二维数组。如

array(1) {

      [0] => array(8)

{ ["rank_id"] => string(3) “151″

["rank_name"] => string(7) “测试9″

["rank_memo"] => string(3) “123″

["uid"] => string(5) “59471″

["rank_kw"] => string(6) “重要”

["rank_uptime"] => string(10) “1280202914″

["isverify"] => string(1) “0″

["ishot"] => string(1) “0″

}

   }

find的效果如下,返回的是一个一维数组:

array(8) {

["rank_id"] => string(3) “151″

["rank_name"] => string(7) “测试9″

["rank_memo"] => string(3) “123″

["uid"] => string(5) “59471″

["rank_kw"] => string(6) “重要”

["rank_uptime"] => string(10) “

1280202914″ ["isverify"] => string(1) “0″

["ishot"] => string(1) “0″

}


Where方法:用于查询或者更新条件的定义

Table方法:定义要操作的数据表名称
$Model->Table(‘think_user user’)->where(‘status>1′)->select();

field方法:定义要查询的字段
field方法的参数支持字符串和数组,例如,
$Model->field(‘id,nickname as name’)->select();
$Model->field(array(‘id’,'nickname’=>’name’))->select();
如果不使用field方法指定字段的话,默认和使用field(‘*’)等效。


U更新,C创建:

data,add,save方法:数据对象赋值,添加,保存。例如:
$data['name'] = ‘ThinkPHP’;
$data['email'] = [email protected];
$Model->data($data)->add();//新增,相当于insert,连贯写法
$Model->add($data); //新增,相当于insert,非连贯写法
$Model->data($data)->where(‘id=3′)->save(); //修改,相当于update

需要注意的是,save方法的话,如果数据没有变化,那么默认返回的操作是FALSE。但是这个save执行是OK的,这个需要注意。

create->()自动从POST的字段组成形如$data的数据

$User=D("User");
$User->create(); //默认通过表单提交的数据进行创建
$User->add(); //新增

如果你癿主键是自劢增长类型,幵丏如果揑入数据成功癿话,Add方法癿迒回值就是最新揑入癿主键值,可以直接获叏。  

使用data方法创建癿数据对象丌会迕行自劢验证和过滤操作,请自行处理。但在迕行add戒者
save操作癿旪候,数据表中丌存在癿字段以及非法癿数据类型(例如对象、数组等非标量数据)是会自
劢过滤癿,丌用担心非数据表字段癿写入导致 SQL错诣癿问题。 

我们熟恲癿令牉验证、自劢验证和自劢完成(我们会在后面看刡相关癿用法)功能,其实都
必须通过create方法才能生效。Create方法创建癿数据对象是保存在内存中,幵没有实际写入刡数据库
中,直刡使用add戒者save方法。如果叧是想简单创建一个数据对象,幵丌需要完成一些额外癿功能
癿话,可以使用data方法简单癿创建数据对象。


setInc和setDec方法。对于统计字段(通常指的是数字类型)的更新:
$Model->setInc(‘score’,'id=5′,3); // 用户的积分加3
$Model->setInc(‘score’,'id=5′); // 用户的积分加1
$Model->setDec(‘score’,'id=5′,5); // 用户的积分减5
$Model->setDec(‘score’,'id=5′); // 用户的积分减1

D删除:

delete->()删除数据
$User->where(‘status=0′)->order(‘create_time’)->limit(’5′)->delete();

Model的其他常见方法:

order方法:结果排序 例如:
order(‘id desc’)
排序方法支持对多个字段的排序
order(‘status desc,id asc’)
order方法的参数支持字符串和数组,数组的用法如下:
order(array(‘status’=>’desc’,'id’))

limit方法:结果限制
limit(’1,10′)
如果使用limit(’10′) 等效于 limit(’0,10′)

page方法:查询分页,Page方法的用法和limit方法类似,格式为:
Page(‘page[,listRows]‘)
Page表示当前的页数,listRows表示每页显示的记录数。例如表示每页显示10条记录的情况下面,获取第2页的数据:
Page(’2,10′)
listRow如果不写的话,会读取limit(‘length’) 的值,例如表示每页显示25条记录的情况下面,获取第3页的数据:
limit(25)->page(3);
如果limit也没有设置的话,则默认为每页显示20条记录。

Join方法查询Join支持.Join方法的参数支持字符串和数组,并且join方法是连贯操作中唯一可以多次调用的方法。例如:
$Model->join(‘ work ON artist.id = work.artist_id’)->join(‘card ON artist.card_id = card.id’)->select();
默认采用LEFT JOIN 方式,如果需要用其他的JOIN方式,可以改成
$Model->join(‘RIGHT JOIN work ON artist.id = work.artist_id’)->select();

Distinct方法查询的Disiinct支持。查询数据的时候进行唯一过滤
$Model->Distinct(true)->select();

Relation方法关联查询支持
$Model->Relation(true)->select();


条件查询

$map->put('name','php'); //name='php'

('name',array('like','think')); //name like '...' 

('id',array('in',array(1,2,4))); 

('id',array('10','3','or')); //id>=10 or


thinkphp多表查询语句

 

1、table()函数

thinkphp中提供了一个table()函数,具体用法参考以下语句:

$list=$Demo->table('think_blog blog,think_type type')->where('blog.typeid=type.id')->field('blog.id as id,blog.title,blog.content,type.typename as type')->order('blog.id desc' )->limit(5)->select();

echo $Demo->getLastSql(); //打印一下SQL语句,查看一下

 

2、join()函数

看一下代码:

$Demo = M('artist');

$Demo->join('RIGHT JOIN think_work ON think_artist.id = think_work.artist_id' );

//可以使用INNER JOIN 或者 LEFT JOIN 这里一定要注意表名的前缀!

echo $Demo->getLastSql(); //打印一下SQL语句,查看一下




附最简单的增删查改的代码

[php] view plaincopy
  1. // 查询数据  
  2. public function index(){  
  3.     $Form   = M("Form");  
  4.     $list   =   $Form->limit(5)->order('id desc')->findAll();  
  5.     $this->assign('list',$list);  
  6.     $this->display();  
  7. }  
  8. // 写入数据  
  9. public function insert() {  
  10.     $Form   =   D("Form");  
  11.     if($vo = $Form->create()) {  
  12.         $list=$Form->add();  
  13.         if($list!==false){  
  14.             $this->success('数据保存成功!');  
  15.         }else{  
  16.             $this->error('数据写入错误!');  
  17.         }  
  18.     }else{  
  19.         $this->error($Form->getError());  
  20.     }  
  21. }  
  22.   
  23. // 更新数据  
  24. public function update() {  
  25.     $Form   =   D("Form");  
  26.     if($vo = $Form->create()) {  
  27.         $list=$Form->save();  
  28.         if($list!==false){  
  29.             $this->success('数据更新成功!');  
  30.         }else{  
  31.             $this->error("没有更新任何数据!");  
  32.         }  
  33.     }else{  
  34.         $this->error($Form->getError());  
  35.     }  
  36. }  
  37. // 删除数据  
  38. public function delete() {  
  39.     if(!emptyempty($_POST['id'])) {  
  40.         $Form   =   M("Form");  
  41.         $result =   $Form->delete($_POST['id']);  
  42.         if(false !== $result) {  
  43.             $this->ajaxReturn($_POST['id'],'删除成功!',1);  
  44.         }else{  
  45.             $this->error('删除出错!');  
  46.         }  
  47.     }else{  
  48.         $this->error('删除项不存在!');  
  49.     }  


Statement
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
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment