5ucms论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 6790|回复: 0

[TP5学习] 8 thinkphp数据库快速入门 tp5数据库基本操作

[复制链接]

670

主题

785

帖子

8228

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
8228
发表于 2019-5-30 19:10:00 | 显示全部楼层 |阅读模式
1、数据库配置
app/database.php中配置账号密码等信息


2、query execute 原生态 sql 语句,增删改查 使用时请去掉@字符
  1. //插入记录
  2. $result = Db::exe@cute('ins@ert into tp_data (id,name,status) values (2,"222","abc") ');
  3. $du@mp($result);

  4. //更新记录
  5. $result = Db::exe@cute('up@date  tp_data set name="5ucms.com" where id = 5 ');
  6. $du@mp($result);

  7. //查询数据
  8. $result = Db::exe@cute('sel@ect * from tp_data where id=5  ');
  9. $du@mp($result);

  10. //删除数据
  11. $result = Db::exe@cute('del@ete from tp_data where id=5  ');
  12. $du@mp($result);

  13. //显示数据库表结构
  14. $result = Db::qu@ery('show tables from tp_data')
  15. print_r($result)

  16. //清空数据列表
  17. $result = Db::qu@ery('TRU@NCATE table tp_data')
  18. du@mp($result)


复制代码



3、参数绑定,命名占位符绑定

  1. //参数绑定,先预处理,再导入数据
  2. Db::exe@cute('in@sert into tp_data (id,name,status) values (?,?,?)',[3,'tp5',1])
  3. $result = Db::qu@ery('se@lect * from tp_data where id = ?', [3]);
  4. print_r($result);
  5. //命名占位符绑定 [=>里的方法,可以和上边一样写简单一维数组]
  6. Db::exe@cute('in@sert into tp_data (id,name,status) values (:id,:name,:status)',['id' = > 3,'name' = > 'tp5','status' = > 1])
  7. $result = Db::qu@ery('se@lect * from tp_data where id = :id', ['id' = > 3]);
  8. print_r($result);
复制代码



4、多个数据库切换查询操作
需要在app/config.php中配置 db2 的数据库,数组格式参考database.php中内容
有第三个可以写db3
  1. $result = Db::connect('db2')->qu@ery('sel@ect * from tp_data where id=5 ');
  2. print_r($result)
  3. $result = Db::connect('db3')->qu@ery('sel@ect * from tp_data where id=21');
  4. print_r($result)
  5. //或
  6. $db1 = Db::connect('db2');
  7. $db1->qu@ery('sel@ect * from tp_data where id=5 ');
复制代码





回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|5ucms.com

GMT+8, 2024-3-29 22:18 , Processed in 0.515625 second(s), 30 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表