開啟debug調試模式(正式上線建議關閉)
config.php
// 應用調試模式
'app_debug' => true,
設置輸出類型
index.php
namespace app\index\controller;
class Index
{
public function index()
{
$data = ['name' => 'steven', 'age' => 24];
return json(['code' => 0, 'msg' => '操作成功', 'data' => $data]);
}
}
或者config.js
// 默認輸出類型, 可選html,json xml ...
'default_return_type' => 'json',
獲取請求參數
引入使用: use think\Request;
namespace app\index\controller;
use think\Request;
class Index {
public function index() {
$res = Request::instance();
// 注意連接字符串用'.',為不是'+'
echo '請求方法: ' . $res->method() . '
';
echo '訪問地址: ' . $res->ip() . '
';
echo '請求參數: ';
dump($res->param());
echo '請求參數(僅包含id): ';
dump($res->only(['id']));
echo '請求參數(排除id): ';
dump($res->except(['id']));
}
}
捕獲.PNG
判斷請求類型
if ($res->isGet()) echo '這是GET方法';
if ($res->isPost()) echo '這是POST方法';
驗證參數數據
use think\Validate;
$rules = [
'name' => 'require',
'age' => 'number|between:0,120',
'email' => 'email'
];
$msg = [
'name.require' => '姓名不能為空',
'age.number' => '年齡必須為數字類型',
'age.between' => '年齡范圍1-120',
'email' => '郵箱格式不正確'
];
// 注意post后有個點
$data = input('post.');
$validate = new Validate($rules, $msg);
$res = $validate->check($data);
if(!$res){
echo $validate->getError();
}
鏈接MySQL數據庫
database.php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st
// +----------------------------------------------------------------------
return [
// 數據庫類型
'type' => 'mysql',
// 服務器地址
'hostname' => '127.0.0.1',
// 數據庫名
'database' => 'test',
// 用戶名
'username' => 'root',
// 密碼
'password' => '***',
... ...
index.php
use think\Db;
$res = Db::query('select * from user');
return $res;