視頻學習地址:
http://study.163.com/course/courseMain.htm?courseId=1004171002
源碼和文檔(如果滿意,歡迎 star):
https://github.com/RiversCoder/tp5-api
百度雲盤鏈接:https://pan.baidu.com/s/1jMNumEOJ2yO5kSKYfnGjOw 密碼:l8qr
看雲文檔:
學習筆記:
sublime 3下載地址:
thinkphp的報錯信息只支持,string,數字,空,回調函數,不支持數組
**原生sql語句查詢**
如果要返回數組格式的數據,需要用json或者json_encode();一下
1 <?php 2 namespace app\index\controller; 3 class Index { 4 public function index() { 5 $data = array( 6 'name' => 'red_panda', 7 'address' => 'China', 8 ); 9 $code = 200; 10 $msg = 'ok'; 11 return json_encode(['data' => $data, 'code' => $code, 'message' => $msg]); 12 } 13 }
config.php里可以改輸出的類型(這樣就可以直接return array了).
'default_return_type'=>'json' // html/json/xml/
獲取參數:
1 <?php 2 namespace app\index\controller; 3 use \think\Request; 4 class Index { 5 public function index() { 6 $request = Request::instance(); 7 echo '請求方法:' . $request->method() . '<br/>'; 8 echo '訪問地址:' . $request->ip() . '<br/>'; 9 echo '請求參數:'; 10 dump($request->param()); 11 echo '請求參數:僅包含name,sex'; 12 dump($request->only(['name', 'sex'])); 13 echo '請求參數:排除name,sex'; 14 dump($request->except(['name', 'sex'])); 15 } 16 }
效果:

postman post請求方法:

返回參數:

thinkphp5里判斷請求方法:
1 <?php 2 namespace app\index\controller; 3 use \think\Request; 4 class Test { 5 public function index() { 6 $request = Request::instance(); 7 // 是否為 GET 請求 8 if (Request::instance()->isGet()) echo "當前為 GET 請求"; 9 // 是否為 POST 請求 10 if (Request::instance()->isPost()) echo "當前為 POST 請求"; 11 // 是否為 PUT 請求 12 if (Request::instance()->isPut()) echo "當前為 PUT 請求"; 13 // 是否為 DELETE 請求 14 if (Request::instance()->isDelete()) echo "當前為 DELETE 請求"; 15 // 是否為 Patch 請求 16 if (Request::instance()->isPatch()) echo "當前為 PATCH 請求"; 17 } 18 }
參數驗證規則:
1 <?php 2 namespace app\index\controller; 3 use \think\Validate; 4 class Test { 5 public function index() { 6 $rule = [ 7 //utf-8 一個字符對應3個字母/數字 對應2個漢字(所以這里可以入3個字母/數字或者一個漢字) 8 'name' => 'require|max:3', 9 'age' => 'number|between:1,120', 10 'email' => 'email', 11 ]; 12 $msg = [ 13 'name.require' => '名稱必須', 14 'name.max' => '名稱最多不能超過3個字符', 15 'age.number' => '年齡必須是數字', 16 'age.between' => '年齡只能在1-120之間', 17 'email' => '郵箱格式錯誤', 18 ]; 19 $data = input('post.'); 20 $validate = new Validate($rule, $msg); 21 $result = $validate->check($data); 22 if (!$result) { 23 dump($validate->getError()); 24 } 25 } 26 }
效果:

**連接數據庫**
/* 數據庫設置 */ 'database' => [ // 數據庫類型 'type' => 'mysql', // 服務器地址 'hostname' => '127.0.0.1', // 數據庫名 'database' => 'thinkphp', // 數據庫用戶名 'username' => 'root', // 數據庫密碼 'password' => '', // 數據庫連接端口 'hostport' => '', // 數據庫連接參數 'params' => [], // 數據庫編碼默認采用utf8 'charset' => 'utf8', // 數據庫表前綴 'prefix' => '', // 數據庫調試模式 'debug' => false, ],
1 <?php 2 namespace app\index\controller; 3 use think\Db; 4 class Index 5 { 6 public function index() 7 { 8 $res = Db::query('select version()'); 9 return $res; 10 } 11 }
設置路由:

