tp5框架增删改查,相对于以前的源生代码而言,非常简单,主要是为了熟练的应用框架,下面的代码主要是tp5框架的增删改查,让我们的更好 掌握框架。
<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
class Index extends Controller
{
public function index(){
return view("index");
}
//添加
public function add(){
$data = Request::instance()->param();
$res = Db::table('yun')->insert($data);
if($res){
return $this->success("添加成功","show");
}else{
return $this->success("添加失败","index");
}
}
//展示
public function show(){
$data = Db::table("yun")->order('id asc')->select();
return view("show",['data'=>$data]);
}
//删除
public function del(){
$id=Request::instance()->param("id");
$res=Db::table("yun")->where('id',$id)->delete();
if($res){
return $this->success("删除成功","show");
}else{
return $this->success("删除失败","show");
}
}
//查询单条数据
public function update(){
$id=Request::instance()->param("id");
$data = Db::table("yun")->where('id',$id)->find();
return view("update",['data'=>$data]);
}
//修改
public function updates(){
$id=Request::instance()->param("id");
$data=Request::instance()->param();
$res=Db::table("yun")->where('id',$id)->update($data);
if($res){
return $this->success("修改成功","show");
}else{
return $this->success("修改失败","show");
}
}
}
表单的提交
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<center>
<form action="{:url('index/add')}" method="post">
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="添加"></td>
</tr>
</table>
</form>
</center>
</body>
</html>
数据的展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<table>
<tr>
<td>ID</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>地址</td>
<td>操作</td>
</tr>
{volist name="data" id="vo"}
<tr>
<td>{$vo.id}</td>
<td>{$vo.name}</td>
<td class="sex" id="{$vo.id}">
{if condition="$vo.sex eq 0 "} 男
{elseif condition="$vo.sex eq 1"}女
{/if}
</td>
<td>{$vo.age}</td>
<td>{$vo.address}</td>
<td>
<a href="{:url('index/del')}?id={$vo.id}">删除</a>
<a href="{:url('index/update')}?id={$vo.id}">修改</a>
</td>
</tr>
{/volist}
</table>
</center>
</body>
</html>
单条数据的遍历
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<center>
<form action="{:url('index/updates')}" method="post">
<input type="hidden" name="id" value="{$data['id']}">
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="name" value="{$data['name']}"></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="age" value="{$data['age']}"></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="address" value="{$data['address']}"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="修改"></td>
</tr>
</table>
</form>
</center>
</body>
</html>