PHP框架-thinkphp-学习笔记-CURD(1)

最近这段时间学习thinkphp,感觉确实是很好用的。不过在学习过程中也遇到了一些问题,现在写出来和大家一起分享;

实验目标:表的CURD。
目标及条件:
1. 主键用guid方式,也就是webid能自动以guid进行填充;
2. 插入时能自动填写一些默认值,比如:新增时,字段: isEnabled=1, dataStatus=1,更新时根据实际值改变。
3. 插入时crtDate,updDate自动插入当前时间。
4. 更新时updDate会自动更新当前时间,crtDate不变。
5. 插入和更新时pinyin字段能根据webname字段的值自动填充。

环境:php 5.2.17; think3.12; mysql 5.0.1b


1.创建表

点击(此处)折叠或打开

  1. drop table if exists ebook_webinfo;

  2. /*==============================================================*/
  3. /* Table: ebook_webinfo */
  4. /*==============================================================*/
  5. create table ebook_webinfo
  6. (
  7.    webId varchar(64) not null comment \'guid\',
  8.    webAddr varchar(100) comment \'范例:www.webset.com\',
  9.    webName varchar(100) comment \'网站名称\',
  10.    pinYin varchar(100) comment \'拼音码\',
  11.    crtDate datetime comment \'创建时间\',
  12.    updDate datetime comment \'最后修改时间\',
  13.    isEnabled int comment \'启用\',
  14.    dataStatus int comment \'数据状态\',
  15.    primary key (webId)
  16. );

2. CURD: 
创建如下php文件,记得要有thinkphp类库哦:)
1.创建Lib->Action->WebinfoAction.class.php, 注意大小写。
2.创建Lib->Model->WebinfoModel.class.php
3.创建Tpl->Webinfo目录,以及下面的add.html, edit.html文件。

PHP框架-thinkphp-学习笔记-CURD(1)_第1张图片


2.1 WebinfoAction.class.php

点击(此处)折叠或打开

  1. class WebinfoAction extends Action{

    private  $tablename = 'Webinfo';

    public function __construct()
    {
    }

    public function index()
    {
      // 使用视图显示, Tpl/Webinfo/index.html
      $this->name = $this->tablename; // 进行模板变量赋值
     
      // 读取数据库
      $Data = M($this->tablename); // 实例化Data数据模型
      $this->data = $Data->select();
      $this->display();
    }

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

    // 该处的id不能变
    public function edit($id=0){
      $Form   =   M($this->tablename);
      echo $id;
      $this->vo   =   $Form->find($id);
      $this->display();
    }
    public function update(){
      $Form   =   D($this->tablename);

      if($Form->create()) {
        $result =   $Form->save();
        if($result) {
          $this->success('操作成功!');
        }else{
          $this->error('写入错误!');
        }
      }else{
        $this->error($Form->getError());
      }
    }
    }

index.html

点击(此处)折叠或打开

  1. <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">
  2. <html>
  3. <head>
  4. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
  5. <title>hello {$name}</title>
  6. </head>
  7. <body>
  8.     

你可能感兴趣的:(PHP框架-thinkphp-学习笔记-CURD(1))