ThinkPHP3.1 Data CURD Operation Quick Start_PHP Tutorial

WBOY
Release: 2016-07-13 10:24:28
Original
964 people have browsed it

1.CURD Overview:

CURD is an abbreviation in database technology. The basic functions of various parameters in general project development are CURD. It represents Create, Update, Read and Delete operations. CURD defines basic atomic operations for processing data. The reason why CURD is elevated to the level of a technical difficulty is that the performance of completing an aggregation-related activity involving CURD operations in multiple database systems may vary greatly as the data relationships change.

CURD does not necessarily use the create, update, read and delete methods in specific applications, but the functions they complete are the same. For example, ThinkPHP uses the add, save, select, and delete methods to represent the CURD operations of the model.

2. Create data

In most cases, the Create operation of CURD usually submits data through a form. First, we create an add.html template file under the Tpl/Form directory of the project with the content:

<FORM method="post" action="__URL__/insert">
标题:<INPUT type="text" name="title"><br/>
内容:<TEXTAREA name="content" rows="5" cols="45"></TEXTAREA><br/>
 <INPUT type="submit" value="提交">
 </FORM>

Copy after login

Then, we also need to create a FormAction.class.php file under the Action directory of the project. For the time being, we only need to define the FormAction class and do not need to add any operation methods. The code is as follows:

class FormAction extends Action{
 }

Copy after login

Next, visit:

http://localhost/app/index.php/Form/add

Copy after login

You can see the form page. We have not defined the add operation method in the controller, but obviously the access is normal. Because ThinkPHP will check whether the corresponding template file exists if it does not find the corresponding operation method. Since we have the corresponding add template file, the controller directly renders the template file and outputs it. So for operation methods without any actual logic, we only need to directly define the corresponding template file.
We can see that the submission address defined in the form is the insert operation to the Form module. In order to process the form submission data, we need to add the insert operation method in the FormAction class, as follows:

class FormAction extends Action{
  public function insert(){
    $Form  =  D('Form');
    if($Form->create()) {
      $result =  $Form->add();
      if($result) {
        $this->success('操作成功!');
      }else{
        $this->error('写入错误!');
      }
    }else{
      $this->error($Form->getError());
    }
  }
 }

Copy after login

If your primary key is an auto-increment type, the return value of the add method is the value of the primary key. If it is not an auto-incrementing primary key, the return value indicates the number of inserted data. If false is returned, it indicates a writing error.

3. Model

In order to facilitate testing, we first create a think_form table in the database:

CREATE TABLE IF NOT EXISTS `think_form` (
 `id` smallint(4) unsigned NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 `content` varchar(255) NOT NULL,
 `create_time` int(11) unsigned NOT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;

Copy after login

We used the D function in the insert operation method. Unlike the M function, the D function requires a corresponding model class. Let’s create the model class below. The definition specification of the model class is:
Model name + Model.class.php (The model name is defined in camel case and the first letter is capitalized)
We create the FormModel.class.php file under the Lib/Model directory of the project and add the following code:

class FormModel extends Model {
  // 定义自动验证
  protected $_validate  =  array(
    array('title','require','标题必须'),
    );
  // 定义自动完成
  protected $_auto  =  array(
    array('create_time','time',1,'function'),
    );
 }

Copy after login

It is mainly used for automatic verification and automatic completion of forms. We will describe the specific usage separately in another space, so we will skip it here for now. What we only need to understand is that if you use the D function to instantiate a model class, it generally needs to correspond to a data model class, and the create method will automatically verify and automatically complete the data submitted by the form (if defined), if the automatic verification fails , you can get the verification prompt information through the model's getError method. If the verification passes, it means that the data object has been successfully created, but it is currently only saved in memory until we call the add method to write the data to the database. This completes a complete Create operation, so you can see that ThinkPHP uses two steps in the process of creating data:

The first step is to create a data object using the create method,
In the second step, use the add method to write the current data object into the database.

Of course, you can skip the first step and go directly to the second step, but this kind of preprocessing has several advantages:

1. No matter how complex the form is, the create method can easily create a data object with one line of code;
2. Before writing data, you can verify and supplement the data;
In fact, the create method also has many functional operations, with only one purpose, to ensure that the data written to the database is safe and effective.

Let’s verify the effect of form submission. When we submit the form directly without entering a title, the system will give a prompt message that the title must be like this.
When we successfully submit the form, we will see that the create_time field in the data written to the data table already has a value. This is written through the automatic completion of the model.

If your data is written entirely internally rather than through a form (that is, you can fully trust the security of the data), you can use the add method directly, such as:

$Form  =  D('Form');
$data['title'] =  'ThinkPHP';
$data['content']  =  '表单内容';
$Form->add($data);

Copy after login

Also supports object-based operations:

$Form  =  D('Form');
$Form->title =  'ThinkPHP';
$Form->content  =  '表单内容';
$Form->add();
Copy after login

对象方式操作的时候,add方法无需传入数据,会自动识别当前的数据对象赋值。

4.读取数据

当我们成功写入数据后,就可以进行数据读取操作了。在前面一篇中,我们已经知道可以用select方法获取数据集,这里我们来通过find方法获取一个单一数据,定义read操作方法如下:

public function read($id=0){
  $Form  =  M('Form');
  // 读取数据
  $data =  $Form->find($id);
  if($data) {
    $this->data =  $data;// 模板变量赋值
  }else{
    $this->error('数据错误');
  }
  $this->display();
 }

Copy after login

read操作方法有一个参数$id,表示我们可以接受URL里面的id变量(后面我们会在变量章节详细描述。这里之所以用M方法而没有用D方法,是因为find方法是基础模型类Model中的方法,所以没有必要浪费开销去实例化FormModel类(即使已经定义了FormModel类)。我们通常采用find方法读取某个数据,这里使用了AR模式来操作,所以没有传入查询条件,find($id) 表示读取主键为$id值的数据,find方法的返回值是一个如下格式的数组:

array(
  'id'    => 5,
  'title'   => '测试标题',
  'content'  => '测试内容',
  'status'  => 1,
 )

Copy after login

然后我们可以在模板中输出数据,添加一个read模板文件:

<table>
 <tr>
  <td>id:</td>
  <td>{$data.id}</td>
 </tr>
 <tr>
  <td>标题:</td>
  <td>{$data.title}</td>
 </tr>
 <tr>
  <td>内容:</td>
  <td>{$data.content}</td>
 </tr>
 </table>

Copy after login

完成后,我们就可以访问

http://localhost/app/index.php/Form/read/id/1

Copy after login

来查看了。
如果你只需要查询某个字段的值,还可以使用getField方法,例如:

$Form = M("Form"); 
 // 获取标题 
$title = $Form->where('id=3')->getField('title');

Copy after login

上面的用法表示获取id值为3的数据的title字段值。其实getField方法有很多用法,但是获取某个字段的值是getField方法最常规的用法。
查询操作是最常用的操作,尤其是涉及到复杂的查询条件,我们会在查询语言一章对查询进行更加详细的讲解。

5.更新数据

在成功写入并读取数据之后,我们就可以对数据进行编辑操作了,首先我们添加一个编辑表单的模板文件edit.html,如下:

 <FORM method="post" action="__URL__/update">
  标题:<INPUT type="text" name="title" value="{$vo.title}"><br/>
  内容:<TEXTAREA name="content" rows="5" cols="45">{$vo.content}</TEXTAREA><br/>
  <INPUT type="hidden" name="id" value="{$vo.id}">
  <INPUT type="submit" value="提交">
 </FORM>

Copy after login

编辑模板不同于新增表单,需要对模板进行变量赋值,所以,我们这次需要在FormAction类添加两个操作方法:

public function edit($id=0){
  $Form  =  M('Form');
  $this->vo  =  $Form->find($id);
  $this->display();
 }
 public function update(){
  $Form  =  D('Form');
  if($Form->create()) {
    $result =  $Form->save();
    if($result) {
      $this->success('操作成功!');
    }else{
      $this->error('写入错误!');
    }
  }else{
    $this->error($Form->getError());
  }
 }

Copy after login

完成后,我们就可以访问

http://localhost/app/index.php/Form/edit/id/1
Copy after login


数据的更新操作在ThinkPHP使用save方法,可以看到,我们同样可以使用create方法创建表单提交的数据,而save方法则会自动把当前的数据对象更新到数据库,而更新的条件其实就是表的主键,这就是我们在编辑页面要把主键的值作为隐藏字段一起提交的原因。
如果更新操作不依赖表单的提交的话,就可以写成:

$Form = M("Form"); 
 // 要修改的数据对象属性赋值
$data['id'] = 5;
$data['title'] = 'ThinkPHP';
$data['content'] = 'ThinkPHP3.1版本发布';
$Form->save($data); // 根据条件保存修改的数据

Copy after login

save方法会自动识别数据对象中的主键字段,并作为更新条件。当然,你也可以显式的传入更新条件:

$Form = M("Form"); 
 // 要修改的数据对象属性赋值
$data['title'] = 'ThinkPHP';
$data['content'] = 'ThinkPHP3.1版本发布';
$Form->where('id=5')->save($data); // 根据条件保存修改的数据

Copy after login

也可以改成对象方式来操作:

$Form = M("Form"); 
 // 要修改的数据对象属性赋值
$Form->title = 'ThinkPHP';
$Form->content = 'ThinkPHP3.1版本发布';
$Form->where('id=5')->save(); // 根据条件保存修改的数据

Copy after login

数据对象赋值的方式,save方法无需传入数据,会自动识别。
save方法的返回值是影响的记录数,如果返回false则表示更新出错。

有些时候,我们只需要修改某个字段的值,就可以使用setField方法,而不需要每次都调用save方法。

$Form = M("Form"); 
 // 更改title值
$Form->where('id=5')->setField('title','ThinkPHP');

Copy after login

对于统计字段,系统还提供了更加方便的setInc和setDec方法。
例如:

  $User = M("User"); // 实例化User对象
  $User->where('id=5')->setInc('score',3); // 用户的积分加3
  $User->where('id=5')->setInc('score'); // 用户的积分加1
  $User->where('id=5')->setDec('score',5); // 用户的积分减5
  $User->where('id=5')->setDec('score'); // 用户的积分减1

Copy after login


6.删除数据

删除数据很简单,只需要调用delete方法,例如:

$Form = M('Form');
$Form->delete(5);

Copy after login

表示删除主键为5的数据,delete方法可以删除单个数据,也可以删除多个数据,这取决于删除条件,例如:

$User = M("User"); // 实例化User对象
$User->where('id=5')->delete(); // 删除id为5的用户数据
$User->delete('1,2,5'); // 删除主键为1,2和5的用户数据
$User->where('status=0')->delete(); // 删除所有状态为0的用户数据

Copy after login

delete方法的返回值是删除的记录数,如果返回值是false则表示SQL出错,返回值如果为0表示没有删除任何数据。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/825433.htmlTechArticle1.CURD概述: CURD是一个数据库技术中的缩写词,一般的项目开发的各种参数的基本功能都是CURD。它代表创建(Create)、更新(Update)、读取...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!