https://coding.imooc.com/learn/list/97.html
目前包含了Mysql、SqlServer、PgSQL、Sqlite等数据库的支持。
默认是在application\database.php里配置的,
Db::connect($config)->query(‘select * from think_user where id=:id‘,[‘id‘=>8]);
$config是一个单独的数据库配置,支持数组和字符串,也可以是一个数据库连接的配置参数名。
或者使用字符串方式:
Db::connect(‘mysql://root:1234@127.0.0.1:3306/thinkphp#utf8‘);
例子:
$user=\think\Db::connect(‘mysql://root:root@127.0.0.1:3306/tp5#utf8‘)->query(‘select * from user where id=?‘,[$id]);
数据库类型://用户名:密码@数据库地址:数据库端口/数据库名#字符集
详细参考说明文档:
https://www.kancloud.cn/manual/thinkphp5/118059
配置了数据库连接信息后,我们就可以直接使用数据库运行原生SQL操作了,支持query
(查询操作)和execute
(写入操作)方法,并且支持参数绑定。
1 Db::query(‘select * from think_user where id=?‘,[8]); 2 Db::execute(‘insert into think_user (id, name) values (?, ?)‘,[8,‘thinkphp‘]);
也支持命名占位符绑定,例如:
1 Db::query(‘select * from think_user where id=:id‘,[‘id‘=>8]); 2 Db::execute(‘insert into think_user (id, name) values (:id, :name)‘,[‘id‘=>8,‘name‘=>‘thinkphp‘]);
这样就不需要use think\Db; 这句了。
think\Db::query(‘select * from think_user where id=?‘,[8]);
Db::query(‘select * from think_user where name like :name‘,[‘name‘=>‘%德华%‘]);
Db::execute(‘insert into think_user (id, name) values (:id, :name)‘,[‘id‘=>8,‘name‘=>‘thinkphp‘]);
1 <?php 2 namespace app\index\controller; 3 use \think\Controller; 4 use \think\Db; 5 6 class Index extends Controller 7 { 8 public function index() 9 { 10 $data=Db::query(‘select * from sys_user where id=?‘,[1]); 11 dump($data); 12 } 13 }
要实现的功能:
控制器调用model层,从表里查出数据,model层将查出来的结果传给控制器,
控制器再返回json模式的数据
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: Haima 5 * Date: 2018/7/8 6 * Time: 15:58 7 */ 8 9 namespace app\api\controller\v1; 10 use app\api\model\Banner as BannerModel; 11 use app\api\validate\IDMustBePostiveInt; 12 use app\lib\exception\BannerMissException; 13 14 class Banner 15 { 16 /** 17 * 获取指定id的banner信息 18 * @url /banner/:id 19 * @http GET 20 * @id banner的id号 21 */ 22 public function getBanner($id) 23 { 24 25 (new IDMustBePostiveInt())->goCheck(); //验证$id是否为正整数 26 $banner = BannerModel::getBannerById($id);//调用model 27 if (!$banner){ 28 throw new BannerMissException(); //判断结果不存在,抛出异常 29 } 30 return json($banner,200);//返回json格式的结果, 默认就是200状态码,可不写 31 } 32 }
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: Haima 5 * Date: 2018/7/12 6 * Time: 1:16 7 */ 8 9 namespace app\api\model; 10 11 12 use think\Db; 13 14 class Banner 15 { 16 public static function getBannerById($id){ 17 //TODO 根据Banner 的 ID号 获取Banner信息 18 $result=Db::query(‘select * from banner_item where banner_id = ?‘,[$id]); 19 return $result; 20 21 } 22 }
查出了四条数据
z.com/api/v1/banner/1?XDEBUG_SESSION_START=13378
原文:https://www.cnblogs.com/haima/p/HaimaBlog.html