Home>Article>Backend Development> Case study on thinkphp5.0 database operation

Case study on thinkphp5.0 database operation

jacklove
jacklove Original
2018-06-15 11:03:30 3390browse

1. Supported database types

Support for Mysql, SqlServer, pgSQL, Sqlite and other databases

2. How to connect to the database

1. Configuration file definition

a. Configuration file directory
project\application\database.php
b .How to configure

return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => '', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ];

c.How to use

// 实例化系统数据库类$DB=new Db;// 查询数据$data=$DB::table("user")->select();//使用sql语句$data=$DB::query("select * from user");

2.Method configuration

1.Use array

//Db类中的connect方法:数据库初始化 并取得数据库类实例 $DB=Db::connect([ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'edu', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ]);

2. Using strings

//Db类中的connect方法:数据库初始化 并取得数据库类实例$DB=Db::connect("mysql://root:@127.0.0.1:3306/edu#utf8");

3. How to use

$data=$DB->table('user')->select();

3. Model class definition

1. Create Data model

  • a. Command line creation

  • b. Manual creation
    1. Open the data model directory (project\application\index \model)
    2. Create a new file User.php under the directory file
    3. Write code in the file

2. How to set

 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'edu', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ]; //使用字符串 protected $connection="mysql://root:@127.0.0.1:3306/edu#utf8"; }?>

3. How to use

// 使用模型定义连接public function data2(){ echo "使用模型连接数据库"; $user=new \app\index\model\User(); dump($user::all()); }

in the controller 3. Query data

1.tp method

// 实例化系统数据库类$DB=new Db;// 查询数据$data=$DB::table("user")->select();

2. Use sql statements

//使用sql语句$data=$DB::query("select * from user");

4. Basic use of database

Supports query (query operation) and execute (write operation)

0. Get the specified sql statement

// 获取执行的sql语句echo Db::getLastSql();

1. Query

$data=Db::query("select * from user"); $data=Db::query("select * from user where id >=? and id<=?",[5,8]);

2. Add

$data=Db::execute("insert into user value(null,'user1','123','18')"); $data=Db::execute("insert into user value(null,?,?,?)",['user2','123','20']"); $data=Db::execute("insert into user value(null,:name,:pass,:age)",['name'=>'user3','pass'=>'123','age'=>'20']);

3. Delete

$data=Db::execute("delete from user where id=10"); $data=Db::execute("delete from user where id>?",[15]); $data=Db::execute("delete from user where id>:id",['id'=>10]);

4. Modify

$data=Db::execute("update user set age='20' where id=?",[15]);

5. TP data processing

1. Query operation

1.table方法查询数据 // 查询所有数据 $data=Db::table("user")->select(); // 查询一条数据 $data=Db::table("user")->find(); 2.name方法查询数据 //name方法会自动添加上配置文件中的表前缀,与配置文件有关 $data=Db::name("user")->select(); $data=Db::name("user")->find(); 3.助手函数 $data=db("user")->select(); $data=db("user")->find(); 4.where条件匹配 $data=Db::table("user")->where("id",">",5)->select(); $data=Db::table("user")->where("id","<",11)->where("id",">",8)->select(); $data=Db::table("user")->where("name","like","%tian%")->select(); $data=Db::table("user")->where("name","wanlisha")->where("pass","wanlisha")->select(); 5.whereor条件查询 $data=Db::table("user")->where("id","<=",'21')->whereOr("id","<=",5)->select(); $data=Db::table("user")->where("name",'like',"%tian%")->whereOr("name",'like','%wanli%')->select(); $data=Db::table("user")->where("name|pass",'like',"%tian%")->select();// 6.limit截取数据 $data=Db::table("user")->limit(2)->select(); $data=Db::table("user")->limit(0,2)->select(); 7.order实现排序 $data=Db::table("user")->order('id')->select(); $data=Db::table("user")->order("id","desc")->select(); 8.field 设置查询字段 //设置查询字段 $data=Db::table("user")->field('name,pass')->select(); $data=Db::table("user")->field(['name','pass'])->select(); // 给name起别名 $data=Db::table("user")->field('name uname,pass')->select(); $data=Db::table("user")->field(['name'=> 'uname','pass'])->select(); // sql的系统函数 $data=Db::table("user")->field("count(*) as tot")->select(); $data=Db::table("user")->field(["count(*)"=>"tot"])->select(); //排除字段 $data=Db::table("user")->field("name,pass",true)->select(); $data=Db::table("user")->field(["name","pass"],true)->select(); 9.Page实现分页效果 $data=Db::table("user")->page(3,5)->select(); $data=Db::table("user")->page("3,5")->select(); 10.分组聚合 $data=Db::table("user")->field("pass,count(*) tot")->group("pass")->select(); 11.having过滤 // 只能结合分组使用 $data=Db::table("user")->field("pass,count(*) tot")->having("tot >=4")->group("pass")->select(); 12.多表查询 // 内敛实现数据库连接 $data=Db::query("select product.*,fenlei.name tname from fenlei,product where product.cid=fenlei.id"); $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id")->select(); // 右链接 $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id",'right')->select(); // 左链接 $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id",'left')->select(); 13.别名使用-给表起别名 $data=Db::table("product")->alias('p')->field("p.*,f.name fname")->join("fenlei f","p.cid=f.id",'left')->select(); 14.union集合 $data=Db::field("name")->table("user")->union("select name from product")->select(); 15.参数绑定bind为了防止sql注入 //自动轻微防止sql注入 $data=Db::table("user")->where("id",$id)->delete(); //不防注入 建议不要使用原生的sql语句 $data=Db::execute("delete from user where id=$id"); //防注入 $data=Db::table("user")->where("id",":id")->bind(['id'=>[$id,\PDO::PARAM_INT]])->delete(); 16.统计数据 $data=Db::table("user")->max("age"); $data=Db::table("user")->min("age"); $data=Db::table("user")->avg("age"); $data=Db::table("user")->sum("age"); $data=Db::table("user")->count(); 17.视图查询(多表查询) $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid")->select(); // 左连接 $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid","right")->select(); // 右连接 $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid","left")->select();

2. Insert operation

1.插入单条数据 // 数组中的字段名必须和数据库中字段名一致 $data=[ 'name'=>'张三', 'pass'=>'123', 'age'=>18 ]; // 返回值:影响行数 $code=Db::table("user")->insert($data); $code=db("user")->insert($data); 2.插入多条数据 $data=[ [ 'name'=>'张三1', 'pass'=>'123', 'age'=>18 ], [ 'name'=>'张三2', 'pass'=>'123', 'age'=>18 ] ]; //返回值:影响行数 $code=Db::table("user")->insertAll($data); $code=db("user")->insertAll($data); 3.获取最后一次插入的id $data=[ 'name'=>'张三1', 'pass'=>'123', 'age'=>18 ]; $code=Db::table("user")->insertGetId($data); $code=db("user")->insertGetId($data);

3.Update data

1.修改数据 $code=Db::table("user")->where("id",">",5)->update(["age"=>111,"pass"=>'111']); $code=Db::table("user")->update(["id"=>5,"age"=>60]); code=Db::table("user")->where("id",5)->setField("age",111); 2.设置自增 $code=Db::table("user")->where("id",6)->setInc("age"); 3.设置自减 $code=Db::table("user")->where("id",7)->setDec("age"); $code=Db::table("user")->where("id",5)->setDec("age",3);

4. Delete data

1.删除一条数据 $code=Db::table("user")->where("id",6)->delete(); $code=Db::table("user")->delete(7); 2.删除多条数据 $code=Db::table("user")->where("id in(1,2)")->delete(); $code=Db::table("user")->delete([2,3]); 3.删除区间数据 $code=Db::table("user")->where("id>0 and id<5")->delete();

6. Transaction mechanism

1.mysql transaction

The engine that requires data must be InnoDB
Key point: execute the statement on the data table to be operated: ALTER TABLE user ENGINE=INNODB;

2. Use

1. Automatically control transactions

Db::transaction(function(){ // 删除一条数据 Db::table("user")->delete(11); Db::table("user")->deletes(40);});

2. Manually control transactions

// 手动控制事务 // 开启事务 Db::startTrans(); try{ // 删除数据 $a=Db::table("user")->delete(11); // 判断是否删除成功 if(!$a){ throw new \Exception("删除11没有成功"); } // 删除不存在的数据 $b=Db::table("user")->delete(12); if(!$b){ throw new \Exception("删除12没有成功"); } // 执行提交操作 Db::commit();`这里写代码片` echo "成功"; }catch(\Exception $e){ // 回滚事务 echo "失败"; Db::rollback(); dump($e->getmessage()); }

// 开启事务 Db::startTrans(); // 删除数据 $a=Db::table("user")->delete(1); $b=Db::table("user")->delete(2); // 判断条件 if($a && $b){ // 提交事务 Db::commit(); }else{ Db::rollback(); }

1. Supported database types

Support for Mysql, SqlServer, pgSQL, Sqlite and other databases

2. How to connect to the database

1. Configuration file definition

a. Configuration file directory
Project\application\database.php
b.How to configure

return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => '', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ];

c.How to use

// 实例化系统数据库类$DB=new Db;// 查询数据$data=$DB::table("user")->select();//使用sql语句$data=$DB::query("select * from user");

2.Method configuration

1.Use Array

//Db类中的connect方法:数据库初始化 并取得数据库类实例 $DB=Db::connect([ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'edu', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ]);

2.Use string

//Db类中的connect方法:数据库初始化 并取得数据库类实例$DB=Db::connect("mysql://root:@127.0.0.1:3306/edu#utf8");

3.How to use

$data=$DB->table('user')->select();

3.Model class definition

1. Create a data model

  • a. Command line creation

  • b. Manual creation
    1. Open the data model directory (project\application\ index\model)
    2. Create a new file User.php under the directory file
    3. Write code in the file

2. How to set up

 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'edu', // 用户名 'username' => 'root', // 密码 'password' => '', // 端口 'hostport' => '3306', ]; //使用字符串 protected $connection="mysql://root:@127.0.0.1:3306/edu#utf8"; }?>

3. How to use

// 使用模型定义连接public function data2(){ echo "使用模型连接数据库"; $user=new \app\index\model\User(); dump($user::all()); }

in the controller 3. Query data

1.tp method

// 实例化系统数据库类$DB=new Db;// 查询数据$data=$DB::table("user")->select();

2. Use sql statements

//使用sql语句$data=$DB::query("select * from user");

4. Basic use of database

Supports query (query operation) and execute (write operation) )

0.获取指定sql语句

// 获取执行的sql语句echo Db::getLastSql();

1.查询

$data=Db::query("select * from user"); $data=Db::query("select * from user where id >=? and id<=?",[5,8]);

2.增加

$data=Db::execute("insert into user value(null,'user1','123','18')"); $data=Db::execute("insert into user value(null,?,?,?)",['user2','123','20']"); $data=Db::execute("insert into user value(null,:name,:pass,:age)",['name'=>'user3','pass'=>'123','age'=>'20']);

3.删除

$data=Db::execute("delete from user where id=10"); $data=Db::execute("delete from user where id>?",[15]); $data=Db::execute("delete from user where id>:id",['id'=>10]);

4.修改

$data=Db::execute("update user set age='20' where id=?",[15]);

五、TP数据处理

1.查询操作

1.table方法查询数据 // 查询所有数据 $data=Db::table("user")->select(); // 查询一条数据 $data=Db::table("user")->find(); 2.name方法查询数据 //name方法会自动添加上配置文件中的表前缀,与配置文件有关 $data=Db::name("user")->select(); $data=Db::name("user")->find(); 3.助手函数 $data=db("user")->select(); $data=db("user")->find(); 4.where条件匹配 $data=Db::table("user")->where("id",">",5)->select(); $data=Db::table("user")->where("id","<",11)->where("id",">",8)->select(); $data=Db::table("user")->where("name","like","%tian%")->select(); $data=Db::table("user")->where("name","wanlisha")->where("pass","wanlisha")->select(); 5.whereor条件查询 $data=Db::table("user")->where("id","<=",'21')->whereOr("id","<=",5)->select(); $data=Db::table("user")->where("name",'like',"%tian%")->whereOr("name",'like','%wanli%')->select(); $data=Db::table("user")->where("name|pass",'like',"%tian%")->select();// 6.limit截取数据 $data=Db::table("user")->limit(2)->select(); $data=Db::table("user")->limit(0,2)->select(); 7.order实现排序 $data=Db::table("user")->order('id')->select(); $data=Db::table("user")->order("id","desc")->select(); 8.field 设置查询字段 //设置查询字段 $data=Db::table("user")->field('name,pass')->select(); $data=Db::table("user")->field(['name','pass'])->select(); // 给name起别名 $data=Db::table("user")->field('name uname,pass')->select(); $data=Db::table("user")->field(['name'=> 'uname','pass'])->select(); // sql的系统函数 $data=Db::table("user")->field("count(*) as tot")->select(); $data=Db::table("user")->field(["count(*)"=>"tot"])->select(); //排除字段 $data=Db::table("user")->field("name,pass",true)->select(); $data=Db::table("user")->field(["name","pass"],true)->select(); 9.Page实现分页效果 $data=Db::table("user")->page(3,5)->select(); $data=Db::table("user")->page("3,5")->select(); 10.分组聚合 $data=Db::table("user")->field("pass,count(*) tot")->group("pass")->select(); 11.having过滤 // 只能结合分组使用 $data=Db::table("user")->field("pass,count(*) tot")->having("tot >=4")->group("pass")->select(); 12.多表查询 // 内敛实现数据库连接 $data=Db::query("select product.*,fenlei.name tname from fenlei,product where product.cid=fenlei.id"); $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id")->select(); // 右链接 $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id",'right')->select(); // 左链接 $data=Db::table("product")->field("product.*,fenlei.name tname")->join("fenlei","product.cid=fenlei.id",'left')->select(); 13.别名使用-给表起别名 $data=Db::table("product")->alias('p')->field("p.*,f.name fname")->join("fenlei f","p.cid=f.id",'left')->select(); 14.union集合 $data=Db::field("name")->table("user")->union("select name from product")->select(); 15.参数绑定bind为了防止sql注入 //自动轻微防止sql注入 $data=Db::table("user")->where("id",$id)->delete(); //不防注入 建议不要使用原生的sql语句 $data=Db::execute("delete from user where id=$id"); //防注入 $data=Db::table("user")->where("id",":id")->bind(['id'=>[$id,\PDO::PARAM_INT]])->delete(); 16.统计数据 $data=Db::table("user")->max("age"); $data=Db::table("user")->min("age"); $data=Db::table("user")->avg("age"); $data=Db::table("user")->sum("age"); $data=Db::table("user")->count(); 17.视图查询(多表查询) $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid")->select(); // 左连接 $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid","right")->select(); // 右连接 $data=Db::view("goods","id,name,price")->view("type","name","type.id=goods.cid","left")->select();

2.插入操作

1.插入单条数据 // 数组中的字段名必须和数据库中字段名一致 $data=[ 'name'=>'张三', 'pass'=>'123', 'age'=>18 ]; // 返回值:影响行数 $code=Db::table("user")->insert($data); $code=db("user")->insert($data); 2.插入多条数据 $data=[ [ 'name'=>'张三1', 'pass'=>'123', 'age'=>18 ], [ 'name'=>'张三2', 'pass'=>'123', 'age'=>18 ] ]; //返回值:影响行数 $code=Db::table("user")->insertAll($data); $code=db("user")->insertAll($data); 3.获取最后一次插入的id $data=[ 'name'=>'张三1', 'pass'=>'123', 'age'=>18 ]; $code=Db::table("user")->insertGetId($data); $code=db("user")->insertGetId($data);

3.更新数据

1.修改数据 $code=Db::table("user")->where("id",">",5)->update(["age"=>111,"pass"=>'111']); $code=Db::table("user")->update(["id"=>5,"age"=>60]); code=Db::table("user")->where("id",5)->setField("age",111); 2.设置自增 $code=Db::table("user")->where("id",6)->setInc("age"); 3.设置自减 $code=Db::table("user")->where("id",7)->setDec("age"); $code=Db::table("user")->where("id",5)->setDec("age",3);

4.删除数据

1.删除一条数据 $code=Db::table("user")->where("id",6)->delete(); $code=Db::table("user")->delete(7); 2.删除多条数据 $code=Db::table("user")->where("id in(1,2)")->delete(); $code=Db::table("user")->delete([2,3]); 3.删除区间数据 $code=Db::table("user")->where("id>0 and id<5")->delete();

六、事务机制

1.mysql事务

要求数据的引擎必须是InnoDB
重点:对要操作的数据表执行语句:ALTER TABLE user ENGINE=INNODB;

2.使用

1. 自动控制事务

Db::transaction(function(){ // 删除一条数据 Db::table("user")->delete(11); Db::table("user")->deletes(40);});

2. 手动控制事务

// 手动控制事务 // 开启事务 Db::startTrans(); try{ // 删除数据 $a=Db::table("user")->delete(11); // 判断是否删除成功 if(!$a){ throw new \Exception("删除11没有成功"); } // 删除不存在的数据 $b=Db::table("user")->delete(12); if(!$b){ throw new \Exception("删除12没有成功"); } // 执行提交操作 Db::commit();`这里写代码片` echo "成功"; }catch(\Exception $e){ // 回滚事务 echo "失败"; Db::rollback(); dump($e->getmessage()); } // 开启事务 Db::startTrans(); // 删除数据 $a=Db::table("user")->delete(1); $b=Db::table("user")->delete(2); // 判断条件 if($a && $b){ // 提交事务 Db::commit(); }else{ Db::rollback(); }

本文讲解了关于thinkphp5.0数据库操作的案例,更多相关内容请关注php中文网。

相关推荐:

列举ThinkPHP5与ThinkPHP3的一些异同点

创建一个最简单的ThinkPhp项目工程

关于ThinkPHP的增、删、改、查 的一些总结

The above is the detailed content of Case study on thinkphp5.0 database operation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn