<?php namespace app\index\controller; use think\Db; class Index { public function index() { } public function insert() { #插入数据(原生) $result3 = Db::execute('insert user (username) values ("王家逸")'); dump($result3); #插入数据(tp5) $db = db('user'); $result = $db -> insert(['username' => '王家逸(tp5最优写法)']); #插入数据(返回id) $db1 = db('user'); $result1 = $db1 -> insertGetId(['username' => '王家逸4']); dump($result1); #插入多条数据 $data = [ ['username' => '王家逸5'], ['username' => '王家逸6'], ['username' => '王家逸7'], ]; $db2 = db("user"); $result2 = $db2 -> insertAll($data); echo "成功插入" . ($result2) . "条数据。"; } public function update() { echo 'update~'; #更新数据(原生写法) $result = Db::execute('update user set username = "王家逸(更新后)" where id = 1'); echo "成功更新" . $result . "条数据。"; #更新数据(tp5写法) $db = db('user'); $db -> where('id',2) -> update(['username' => '王家逸(更新数据的tp5写法)']); #更新数据(tp5根据主键) Db::name('user') ->update(['username' => '按主键更新','id' => 1]); } public function select() { #查询数据(原生) $result = Db::query('select * from user'); dump($result); echo "<hr />"; #查询数据(tp5) $db = db('user'); $list = $db -> where('id','>',49) -> select(); dump($list); } public function delete() { #删除数据(原生) $result = Db::execute("delete from user where id =62"); echo "成功删除" . $result . "条数据。"; #删除数据(tp5) $db = db('user'); $db -> where('id','>',50) -> delete(); #删除数据(tp5根据主键) db('user') -> delete(50); } #传值插入 public function bianliangInsert($username) { echo "你好," . $username . "!您的文章已发布成功。"; $db = db('user'); $result = $db -> insert(['username' => $username]); } #传值删除 public function bianliangDelete($id) { echo "id为" . $id . "的数据已删除。"; $db = db('user'); db('user') -> delete($id); } }