开启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;