1. 程式人生 > >thinkphp5.0連結mysql資料庫(1)

thinkphp5.0連結mysql資料庫(1)

用thinkphp連線mysql資料庫

1.需要先在application資料夾內的database.php檔案裡新增上自己mysql的使用者名稱、密碼、庫名、資料庫連結引數。

// 資料庫連線引數

 28     'params'         =>[

 29 // 使用長連線

 30         \PDO::ATTR_PERSISTENT =>true,

 31 ],


2.回到自己的controller資料夾內,編輯Index.php檔案。

(1)先匯入兩個類(沒學過php感覺就跟oc裡面的類的宣告一樣)。

<?php
  2 namespace app\demo\controller;
  3 
  4 use think\Controller;
  5 use think\Db;
(2)繼承controller(感覺跟oc裡的繼承是一回事)。

  7 class Indexextends Controller

  8 {

  9 publicfunction index()

 10 {

 11

 12 }

 13 }

(3)現在只要獲取資料庫的資料就行了。

. 7 class Indexextends controller

  8 {

  9 publicfunction index()

 10 {

 11 $result= Db::query('select * from 表名');

 12 return dump($result);   

 13 }

 14 }

(4)好像還有另一種獲取sql資料方式,試試先。

  7 class Index extends controller

  8 {

  9 publicfunction index()

 10 {

 11 /*$result = Db::query('select * from user');

 12         return dump($result);*/

 13 $data= Db::name('表名')-> select();

 14 return dump($data);

 15 }

 16 }

注:這個方法用select()這個函式輸出資料時會輸出全部資料,用find()輸出時只會輸出一條資料。

(5)再添一個連線方法吧,用的是connect()連結資料庫(我一直覺得php裡一串英文跟著個括號的東西跟函式沒什麼兩樣)。

class Index extends controller

  8 {

  9 publicfunction index()

 10 {

 11 /*$result = Db::query('select * from user');

 12         return dump($result);*/

 13 /*$data = Db::name('user') -> select();

 14         return dump($data);*/

 15 $test= Db::connect('mysql://sql使用者名稱:密碼@127.0.0.1:3306/庫名#utf8')->query('select * from 表名');

 14 return dump($test);

 17 }

 18 }

這樣也能連上呢!!!

3.修改mysql的資料好像不能用query('sql語言'),需要用execute('sql語言'),關於execute這個函式就不做示範了以後還會用到,額,在view資料夾裡頭有個index資料夾編輯裡頭的index.html檔案就能美化輸出的資料了,第一篇就寫這些吧。