tp5(thinkPHP5)框架连接数据库的方法示例
发布人:shili8
发布时间:2022-12-01 08:54
阅读次数:18
本文实例讲述了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);
}
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);
}
}
http://yourwebname/public/index.php/index/index/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>
更多关于thinkphp相关内容感兴趣的读者可查看本站专题:《thinkphp入门教程》、《thinkphp模板操作技巧总结》、《thinkphp常用方法总结》、《codeigniter入门教程》、《ci(codeigniter)框架进阶教程》、《zend framework框架入门教程》及《php模板技术总结》。
希望本文所述对大家基于thinkphp框架的php程序设计有所帮助。

