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' ,
]);
$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 $this -> fetch();
}
public function data()
{
$DB = new Db;
$data = $DB ::table( "uu" ) -> select();
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;
use think\Model;
class Index extends Controller
{
public function index()
{
$this -> data();
return $this -> fetch();
}
public function data()
{
$DB = new Db;
$data = $DB ::table( "uu" ) -> select();
$this -> assign( "user" , $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如何连接数据库的详细内容