search
HomeBackend DevelopmentPHP Tutorialthinkphp implements basic addition, deletion, modification and query

thinkphp implements basic addition, deletion, modification and query

Feb 10, 2017 pm 04:52 PM
thinkphpAdd, delete, modify and check

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=&#39;checked&#39;":""}>/>男  
          <input type="radio" name="Sex" value="女" <{$shuju["sex"]?"":"checked=&#39;checked&#39;"}> />女
</p>
<p>民族:
<select name="Nation">
<foreach name="shujun" item="v">
    <if condition="$shuju[&#39;nation&#39;]==$v[&#39;code&#39;]">
        <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>


主页面:

thinkphp implements basic addition, deletion, modification and query

添加数据

thinkphp implements basic addition, deletion, modification and query

thinkphp implements basic addition, deletion, modification and query

Modify data:

thinkphp implements basic addition, deletion, modification and query

thinkphp implements basic addition, deletion, modification and query

##Delete data :

thinkphp implements basic addition, deletion, modification and query

The above are the basic methods and examples of Thinkphp addition, deletion, modification and query brought to you by the PHP Chinese website!


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools