這篇文章將為大家詳細講解有關使用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>
關于使用thinkPHP5框架如何連接數據庫就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。