thinkphp5怎么连接数据库

发布时间:2020-12-18 11:44:27 作者:小新
来源:亿速云 阅读:383

小编给大家分享一下thinkphp5怎么连接数据库,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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

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

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

// 使用方法配置数据库连接
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)写入

<?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、将数据渲染模板页面

<?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

<!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>

以上是“thinkphp5怎么连接数据库”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. thinkphp5使用
  2. 使用Composer安装ThinkPHP5

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

thinkphp5 数据库 thinkph

上一篇:swoole框架怎么用

下一篇:利用tp5框架实现多数据库查询的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》