数据的CURD操作:
1.创建一个表:
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 ;
2.创建FormAction.class.php
<?php 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()); } } public function read($id=0){ $Form = M('Form'); // 读取数据 $data = $Form->find($id); if($data) { $this->data = $data;// 模板变量赋值 }else{ $this->error('数据错误'); } $this->display(); } 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()); } } public function delete($id=0){ $Form = M('Form'); $Form->delete($id); } }
4.FormModel.class.php
class FormModel extends Model { //定义自动验证 protected $_validate = array( array('title','require','标题必须'), ); //定义自动完成 protected $_auto = array( array('create_time','time',1,'function'), ); }
5.add.edit.read三个模板
<html> <head> <title>CURD</title> </head> <body> <FORM method="post" action="insert"> 标题:<INPUT type="text" name="title"><br/> 内容:<TEXTAREA name="content" rows="5" cols="45"></TEXTAREA><br/> <INPUT type="submit" value="提交"> </FORM> </body> </html>
<html> <head> <title>CURD</title> </head> <body> <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> </body> </html>
<html> <head> <title>CURD</title> </head> <body> <FORM method="post" action="/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> </body> </html>
访问地址:
1. http://localhost/app/index.php/Form/add
2. http://localhost/app/index.php/Form/read/id/1
3. http://localhost/app/index.php/Form/edit/id/1
4. http://localhost/app/index.php/Form/delete/id/1