Home  >  Article  >  PHP Framework  >  How to connect thinkphp5 to the database

How to connect thinkphp5 to the database

王林
王林forward
2020-03-05 10:52:444644browse

How to connect thinkphp5 to the database

1. Configuration file directory tp5\application\database.php

Connect through the configuration file. It can also be linked via methods.

The method in the controller is used to connect to the database; the query writing method is slightly different from the system DB class method.

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

(recommended learning tutorial: thinkphp tutorial)

2. Basic usage, addition, deletion, modification and query

The controller uses the configuration file to connect to the database

The file under the controller (tp5\application\index\controller\Index.php )Write

<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
class Index extends Controller
{
  public function index()
  {
    // return &#39;上课来&#39;;
    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. Render the data to the template page

<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
// 使用model连接数据库要引入moadel
use think\Model;
class Index extends Controller
{
  public function index()
  {
    // return &#39;s&#39;;
    $this -> data();
    return $this -> fetch();
  }
// 使用系统配置文件连接数据库
  public function data()
  {
    // 实例化数据库系统类
    $DB = new Db;
    // 查询数据
    $data = $DB::table("uu") -> select();
    $this -> assign("user",$data);
    // dump($data);
  }
}

4. The template page can reference the rendering data

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>

For more programming-related content, please pay attention to the Introduction to Programming column on the php Chinese website!

The above is the detailed content of How to connect thinkphp5 to the database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete