本文實例講述了thinkPHP5框架連接數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
1、配置文件目錄 tp5\application\database.php
通過配置文件來連接。。
也可以通過方法鏈接
在控制器里方法鏈接數(shù)據(jù)庫 ;查詢時寫法 和使用系統(tǒng)的DB類方法略有差異
// 使用方法配置數(shù)據(jù)庫連接
public function data1 ()
{
$DB = Db::connect([
// 數(shù)據(jù)庫類型
'type' => 'mysql',
// 服務(wù)器地址
'hostname' => '127.0.0.1',
// 數(shù)據(jù)庫名
'database' => 'user',
// 用戶名
'username' => 'root',
// 密碼
'password' => 'root',
// 端口
'hostport' => '3306',
]);
// dump($DB);
// 查詢數(shù)據(jù),,,,和使用系統(tǒng)的DB類方法略有差異
$data = $DB -> table("uu") -> select();
dump($data);
}
2.基本使用 、 增刪改查
控制器使用配置文件連接數(shù)據(jù)庫
控制器下文件(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();
}
// 使用配置文件連接數(shù)據(jù)庫
public function data()
{
// 實例化數(shù)據(jù)庫系統(tǒng)類
$DB = new Db;
// 查詢數(shù)據(jù),表名為uu的所有數(shù)據(jù)
$data = $DB::table("uu") -> select();
// 使用sql語句
//$data = $DB::query("select * from uu");
dump($data);
}
}
http://yourwebname/public/index.php/index/Index/data 獲取數(shù)據(jù)打印測試
3.將數(shù)據(jù)渲染模板頁面
?php
namespace app\index\controller;
use think\Db;
use think\Controller;
// 使用model連接數(shù)據(jù)庫要引入moadel
use think\Model;
class Index extends Controller
{
public function index()
{
// return 's';
$this -> data();
return $this -> fetch();
}
// 使用系統(tǒng)配置文件連接數(shù)據(jù)庫
public function data()
{
// 實例化數(shù)據(jù)庫系統(tǒng)類
$DB = new Db;
// 查詢數(shù)據(jù)
$data = $DB::table("uu") -> select();
$this -> assign("user",$data);
// dump($data);
}
}
4.模板頁面即可引用渲染數(shù)據(jù)
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>
更多關(guān)于thinkPHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術(shù)總結(jié)》。
希望本文所述對大家基于ThinkPHP框架的PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- tp5.1 框架數(shù)據(jù)庫高級查詢技巧實例總結(jié)
- ThinkPHP5.1框架數(shù)據(jù)庫鏈接和增刪改查操作示例
- PHP利用pdo_odbc實現(xiàn)連接數(shù)據(jù)庫示例【基于ThinkPHP5.1搭建的項目】
- PHP7使用ODBC連接SQL Server2008 R2數(shù)據(jù)庫示例【基于thinkPHP5.1框架】
- thinkPHP5實現(xiàn)的查詢數(shù)據(jù)庫并返回json數(shù)據(jù)實例
- tp5(thinkPHP5)框架數(shù)據(jù)庫Db增刪改查常見操作總結(jié)
- tp5(thinkPHP5)框架實現(xiàn)多數(shù)據(jù)庫查詢的方法
- tp5(thinkPHP5)操作mongoDB數(shù)據(jù)庫的方法
- thinkPHP5實現(xiàn)數(shù)據(jù)庫添加內(nèi)容的方法
- thinkPHP5框架數(shù)據(jù)庫連貫操作之cache()用法分析
- thinkPHP5框架實現(xiàn)多數(shù)據(jù)庫連接,跨數(shù)據(jù)連接查詢操作示例
- tp5.1 框架數(shù)據(jù)庫常見操作詳解【添加、刪除、更新、查詢】