<form action="__ACTION__" method="post"> <div>代号:<input type="text" name="Code"/></div> <br/> <div>姓名:<input type="text" name="Name"/></div> <br/> <div>性别: <input type="radio" name="Sex" value="1"/>男 <input type="radio" name="Sex" value="0"/>女 </div> <br/> <div>民族: <select name="Nation"> <foreach name="arr" item="v"> <option value="{$v.code}">{$v.name}</option> </foreach> </select> </div> <br/> <div>生日:<input type="text" name="Birthday"/></div> <br/> <input type="submit" value="添加"/> </form
视图index.html 代码如上,效果:
数据表:
增删改都有三种方法:
1.数组添加
2.映射添加
<?php namespace HomeController; use ThinkController; class IndexController extends Controller { public function add(){ $db = D("Info"); //1.数组方式 $arr = array("Code"=>"p005","Name"=>"随便" ,"Sex"=>1,"Nation"=>"n003","Birthday"=>"1999-02-03"); $db->add($arr); //2.映射方式 $db->Code = "P006"; $db->Name = "测试"; $db->Sex = 1; $db->Nation = "C004"; $db->Birthday = "1996-03-04"; $db->add(); } }
3.自动收集表单:
根据数据表中对应字段收集数据,所以前台页面表单对应的name要与数据表中的字段对应
public function add(){ $db = D("Info"); //3.自动收集表单 if(empty($_POST)){ $arr = $db ->table("Nation") ->select(); $this->assign("arr",$arr); $this->show(); }else{ $db->create();//收集表单 $db->add(); } } }
总体来看,第3种自动收集方式最方便。
修改同理,将最后的$db->add();改成$db->save();
public function update(){ $db = D("Info"); $code = "p002"; if(empty($_POST)){ $nation = $db ->table("Nation") ->select(); $info = $db ->find($code); $this->assign("info",$info); $this->assign("nation",$nation); $this->show(); }else{ $db->create(); $db->save(); } }
删除数据:
public function del(){ //$code = "p006"; $db = D("Info"); //$db->delete($code); $sql = "delete from info where code = 'p004'"; $db->execute($sql); //tp框架也适用sql原生语句,增删改用execute方法执行 ,查数据用query方法执行 } }