找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 php教程 查看内容

thinkphp5如何连接数据库

作者:模板之家 2020-3-5 10:52 3367人关注

本文来自thinkphp教程栏目,文中为大家实例介绍了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>

更多编程相关内容,请关注模板之家(www.mb5.com.cn)编程入门栏目!

以上就是thinkphp5如何连接数据库的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章!


路过

雷人

握手

鲜花

鸡蛋
来自: [db:来源]

全部回复(0)