摘要:本章主要学习tp5.1的数据库的增删改查,通过更改config/database.php下的数据库信息为指定的数据库后,通过tp5.1封装的方法进行增删改查,代码如下:(为方便提交,代码写在index页面)index.php:<?php namespace app\index\controller; use think\Db; use think\Reques
本章主要学习tp5.1的数据库的增删改查,通过更改config/database.php下的数据库信息为指定的数据库后,通过tp5.1封装的方法进行增删改查,代码如下:(为方便提交,代码写在index页面)
index.php:
<?php
namespace app\index\controller;
use think\Db;
use think\Request;
class Index
{
public function index()
{
// 查询构造器执行CURD
$this->execCURD();
}
public function execCURD()
{
//查询单条记录
$res=Db::table('user')->field('name,weight,height')
->where('uid','>',10)
->where('weight','between',[90,100])
->order('weight DESC')
->find();
echo '查询uid大于2,且胸围在90-100,按胸部倒序的单条记录为:'.var_export($res,true);
echo '<br>';
//查询多条记录
$res=Db::table('user')->field('name,weight,height')
->where('height','>=',160)
->order('weight DESC')
->limit(2)
->select();
echo '查询身高大于160,按胸部倒序的前两条记录为:'.var_export($res,true);
echo '<br>';
//执行单条记录插入
$data=[
'name'=>'武藤兰',
'weight'=>90,
'height'=>160,
'add_time'=>time()
];
$num=Db::table('user')
->data($data)
->insert();
$id=Db::getLastInsID();
echo '执行插入的id为:'.$id;
//执行多条记录插入
$data=[
['name'=>'麻美','weight'=>95,'height'=>160,'add_time'=>time()],
['name'=>'爱田由','weight'=>92,'height'=>162,'add_time'=>time()],
['name'=>'松金洋子','weight'=>96,'height'=>165,'add_time'=>time()],
];
Db::table('user')->data($data)->insertAll();
echo '<br>';
echo '执行插入多行记录成功';
//更新操作
$num=Db::table('user')->data(['weight'=>Db::raw('weight+2')])
->where('weight','<',95)
->update();
echo '<br>';
echo '执行更新,胸围小于95的女星,胸围增加2'.($num ? '。更新成功'.$num.'条记录': '。没有记录被更新');
//删除操作
$num=Db::table('user')->where('uid','>',40)->delete();
echo '<br>';
echo '执行删除uid大于48的数据,'.($num ? '删除成功'.$num.'条记录': '没有记录被删除');
}
}执行效果图:

批改老师:韦小宝批改时间:2019-02-21 17:20:20
老师总结:写的很不错 没事的时候要记得多去练习 项目写多了自然技术也就上去了