Home  >  Article  >  Backend Development  >  thinkphp implements basic addition, deletion, modification and query

thinkphp implements basic addition, deletion, modification and query

大家讲道理
大家讲道理Original
2017-02-10 16:52:315067browse

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>主页面</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>添加数据</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>修改数据</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