ThinkPHP5学习(8)数据库-基本操作

来源:互联网 发布:座天使兽网络侦探 编辑:程序博客网 时间:2024/05/19 18:12

学习内容及参考:

视频教程:

http://www.kancloud.cn/tpshop/thinkphp5/221597

http://www.kancloud.cn/tpshop/thinkphp5/221836

完全开发手册:http://www.kancloud.cn/manual/thinkphp5/158834

教程中的代码:https://github.com/phpervip/tp5a


课前准备:

1.安装sql追踪器,

2.了解mysql基础,mysql预处理语句prepare,execute

3.了解mysql事务处理

4.安装使用sqlyong工具。


工欲善其事,必先利其器

mac下sql追踪器的安装,

http://www.tp-shop.cn/index.php/doc/indexbbc/video


https://pan.baidu.com/s/1pK7RhaV?qq-pf-to=pcqq.group

下载phpgjx工具箱,

然后按教程安装即可,当作搭建一个网站。。

本地我把log文件放在,/usr/local/mysql/log/mysql_bz2.log

注意,文件要给777权限。

另外,图片我换成,莲花,大海。

可打包下载我的图片:http://pan.baidu.com/s/1dFy4ENB

搭好的效果。http://www.kancloud.cn/tpshop/thinkphp5/221597.

http://phpgjx.yyii.info

**推荐此工具!**

**能很快看出页面,调用的sql,若sql出现bug,能很快知道在代码哪一句。**

/usr/local/mysql/bin/mysqld,Version: 5.7.16 (MySQL Community Server(GPL)). started with:

Tcpport: 3306 Unix socket: /tmp/mysql.sock

TimeId Command Argument



prepare,是mysql的预处理,

execute,是mysql的执行



事务是一个连续的一组数据库操作,如果事务中某个操作失败,则整个事务失败。



有了上面的基础,就开始学习下面的内容。



1.数据库配置

2.query,execute原生态sql语句,增删改查

3.参数绑定命名占位符绑定

4.多个数据切换查询操作

5.查询构造器

6.DB链式操作

7.事务支持



ThinkPHP内置了抽象数据库访问层,把不同的数据库操作封装起来,我们只需要使用公共的Db类进行操作。



数据库配置。

application/database.php

每个模块可以设置独立的数据库连接参数,admin/database.php



可以采用字符串方式,动态定义连接信息

Db::connect('mysql://root/123456@127.0.0.1:3306/thinkphp#utf8');

如database.php中已经定义好,

可以写:

Db::connect('db_config1);

Db::connect('db_config2);



也可以在模型里单独设置数据库连接信息

创建一个表:

CREATETABLE `tp_user` (

`id`int(11) NOT NULL,

`name`varchar(45) DEFAULT NULL,

`status`tinyint(1) DEFAULT NULL,

`score`tinyint(2) DEFAULT NULL,

`email`varchar(45) DEFAULT NULL,

PRIMARYKEY (`id`)

)ENGINE=InnoDB DEFAULT CHARSET=utf8;



出现:

Class'app\admin\controller\Db' not found

则:

usethink\Db;




<?php// 数据库namespace app\admin\controller;use think\Db;class index2{    // 查询数据     public function test1(){         //  基本使用         // 插入记录             Db::execute('insert into tp_user (id,name) values(?,?)',[8,'thinkphp']);         // 更新记录             Db::execute('update tp_user set name="thinkphp" where id=1 ');         // 查询数据            Db::query('select * from tp_user where id=?',[8]);         // 删除数据            Db::query('delete from tp_user where id=5');         // 显示数据列表            Db::query('show tables from tp5');         // 清空数据表            Db::execute('TRUNCATE table tp_user');         //  命名占位符          Db::query('select * from tp_user where id=:id',[1]);          Db::execute('insert into tp_user (id,name) values(:id,:name)',[8,'thinkphp']);         // 查询构造器         // 查询一个数据         Db::table('tp_user')->where('id',1)->find();         // 找不到返回null         // 查询数据集         Db::table('tp_user')->where('status',1)->select();         // 找不到返回空数组         // 设置了表前缀时         Db::name('user')->where('id',1)->find();         Db::name('user')->where('status',1)->select();         // find,select 方法之前可以使用所有的链式操作方法         // db助手函数         db('user')->where('id',1)->find();         // 使用db助手函数默认每次重新连接数据库,而使用Db::name,或Db::table都是单例的         // 如需要采用相同的链接,可以传入第三个参数。第二个参数为数据库的连接参数         db('user',[],false)->where('id',1)->find();         // 使用query对象或闭包查询         $query = new \think\db\Query();         $query->table('tp_user')->where('status',1);         Db::find($query);        // Db::select($query);         Db::select(function($query){             $query->table('tp_user')->where('status',1);         });         // 返回某个字段值,         Db::table('tp_user')->where('id',1)->value('name');         // 查询某一列的值         Db::table('tp_user')->where('status',1)->column('name');         // 指定索引         Db::table('tp_user')->where('status',1)->column('name','id');                  // 数据集批量处理         Db::table('tp_user')->chunk(100,function($users){             foreach($users as $user){                 //                 echo '1';             }         });         // 或者交给回调方法myUserIterator处理         Db::table('tp_user')->chunk(100,'myUserIterator');         // 你可以通过从闭包函数中返回false来中止对数据集的处理         Db::table('tp_user')->chunk(100,function($users){             // 处理结果集             return false;         });         // 也支持在 chunk 方法之前调用其它的查询方法         Db::table('tp_user')->where('score','>',80)->chunk(100,function($users){             foreach($users as $user){                 //             }         });         // JSON类型数据查询         // 查询JSON类型字段,info字段为json类型         Db::table('tp_user')->where('info$.email','thinkphp@qq.com')->find();     }    // 添加数据     public function test2(){         // 5版本,添加 data/inc/dec/exp方法设置数据         $data = ['foo'=>'bar','bar'=>'foo'];         Db::table('tp_user')->insert($data);         Db::name('user')->insert($data);         // insert 方法添加数据成功返回添加的条数,正常情况返回1         Db::name('user')->insert($data);         $userId = Db::name('user')->getLastInsID();         // 或者直接使用inserGetId方法新增数据并返回主键值         Db::name('user')->insertGetId($data);         // 添加多条数据         $data = [             ['foo'=>'bar','bar'=>'foo'],             ['foo'=>'bar1','bar'=>'foo1'],             ['foo'=>'bar2','bar'=>'foo2'],         ];         Db::name('user')->insertAll($data);         // 助手函数         db('user')->insert($data);         db('user')->insertAll($data);         // 快捷更新         Db::table('user')             ->data(['name'=>'tp','score'=>90])             ->insert();     }     //  更新数据     public function test3(){         Db::table('tp_user')             ->where('id',1)             ->update(['name'=>'thinkphp']);         // 数据中包含主键,直接使用         Db::table('tp_user')             ->update(['name'=>'thinkphp','id'=>1]);         // update方法返回影响数据的条数,没修改任何数据返回0         // 使用Sql函数         Db::table('tp_user')             ->where('id',1)             ->update([                     'login_time'=>['exp','now()'],                     'login_times'=>['exp','login_times+1']                 ]             );         // 更新某个字段的值         Db::table('tp_user')             ->where('id',1)             ->setField('name','thinkphp');         // 自增自减         // setInc/setDec         Db::table('tp_user')             ->where('id',1)             ->setInc('score');         Db::table('tp_user')            ->where('id',1)             ->setInc('score',5);         Db::table('tp_user')             ->where('id',1)             ->setDec('score');         Db::table('tp_user')             ->where('id',1)             ->setDec('score',5);         // 延迟更新         Db::table('tp_user')->where('id',1)->setInc('score',1,10);         // 助手函数         db('user')->where('id',1)->update(['name'=>'thinkphp']);         db('user')->where('id',1)->setField('name','thinkphp');         db('user')->where('id',1)->setInc('score');         db('user')->where('id',1)->setDec('score');         // 快捷更新         Db::table('tp_user')             ->where('id',1)             ->inc('read')             ->dec('score',3)             ->exp('name','UPPER(name)')             ->update();     }}


原创粉丝点击