百搜论坛欢迎您的加入!
adimg adimg
 
昨日:篇  今日:篇   总帖:篇   会员:
博主最大Lv63   
thinkphp5如何连接数据库     

1、配置文件目录 tp5\application\database.php

通过配置文件来连接。也可以通过方法链接。

在控制器里方法链接数据库 ;查询时写法 和使用系统的DB类方法略有差异

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 使用方法配置数据库连接

public function data1 ()

{

  $DB = Db::connect([

    // 数据库类型

    'type'      => 'mysql',

    // 服务器地址

    'hostname'    => '127.0.0.1',

    // 数据库名

    'database'    => 'user',

    // 用户名

    'username'    => 'root',

    // 密码

    'password'    => 'root',

    // 端口

    'hostport'    => '3306',

  ]);

  // dump($DB);

  // 查询数据,,,,和使用系统的DB类方法略有差异

  $data = $DB -> table("uu") -> select();

  dump($data);

}

(推荐学习教程:thinkphp教程

2、基本使用 、 增删改查

控制器使用配置文件连接数据库

控制器下文件(tp5\application\index\controller\Index.php)写入

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?php

namespace app\index\controller;

use think\Db;

use think\Controller;

class Index extends Controller

{

  public function index()

  {

    // return '上课来';

    return $this -> fetch();

  }

  // 使用配置文件连接数据库

  public function data()

  {

    // 实例化数据库系统类

    $DB = new Db;

    // 查询数据,表名为uu的所有数据

    $data = $DB::table("uu") -> select();

    // 使用sql语句

    //$data = $DB::query("select * from uu");

    dump($data);

  }

}

3、将数据渲染模板页面

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<?php

namespace app\index\controller;

use think\Db;

use think\Controller;

// 使用model连接数据库要引入moadel

use think\Model;

class Index extends Controller

{

  public function index()

  {

    // return 's';

    $this -> data();

    return $this -> fetch();

  }

// 使用系统配置文件连接数据库

  public function data()

  {

    // 实例化数据库系统类

    $DB = new Db;

    // 查询数据

    $data = $DB::table("uu") -> select();

    $this -> assign("user",$data);

    // dump($data);

  }

}

4、模板页面即可引用渲染数据

tp5\application\index\view\index\index.html

1

2

3

4

5

6

7

8

9

10

11

12

13

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <title>s</title>

</head>

<body>

  <div> s</div>

  {volist name="user" id="vo"}

    <a href="">{$vo.name}</a>

  {/volist}

</body>

</html>

更多编程相关内容,请关注php中文网编程入门栏目!

以上就是thinkphp5如何连接数据库的详细内容

 0  已被阅读了1186次  楼主 2020-06-23 13:16:18
回复列表

回复:thinkphp5如何连接数据库

联系站长 友链申请桂ICP备19000949号-1     桂ICP备19000949号-1
您的IP:3.17.181.21,2024-04-29 15:50:30,Processed in 0.03133 second(s).
免责声明: 本网不承担任何由内容提供商提供的信息所引起的争议和法律责任。
Powered by HadSky 7.12.9
已有0次打赏
(0) 分享
分享
取消
免责声明
1、本站资源,均来自网络,版权归原作者,所有资源和文章仅限用于学习和研究目的 。
2、不得用于商业或非法用途,否则,一切责任由该用户承担 !
如果觉得本文还不错请点个赞或者打赏点轻币哦~
拒绝伸手党,拿走请回复,尊重楼主,尊重你我他~

侵权删除请致信 E-Mail:207882320@qq.com