request mysql 接口_TP5接口开发
開啟debug調(diào)試模式(正式上線建議關(guān)閉)
config.php
// 應(yīng)用調(diào)試模式
'app_debug' => true,
設(shè)置輸出類型
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
// 默認(rèn)輸出類型, 可選html,json xml ...
'default_return_type' => 'json',
獲取請(qǐng)求參數(shù)
引入使用: use think\Request;
namespace app\index\controller;
use think\Request;
class Index {
public function index() {
$res = Request::instance();
// 注意連接字符串用'.',為不是'+'
echo '請(qǐng)求方法: ' . $res->method() . '
';
echo '訪問地址: ' . $res->ip() . '
';
echo '請(qǐng)求參數(shù): ';
dump($res->param());
echo '請(qǐng)求參數(shù)(僅包含id): ';
dump($res->only(['id']));
echo '請(qǐng)求參數(shù)(排除id): ';
dump($res->except(['id']));
}
}
捕獲.PNG
判斷請(qǐng)求類型
if ($res->isGet()) echo '這是GET方法';
if ($res->isPost()) echo '這是POST方法';
驗(yàn)證參數(shù)數(shù)據(jù)
use think\Validate;
$rules = [
'name' => 'require',
'age' => 'number|between:0,120',
'email' => 'email'
];
$msg = [
'name.require' => '姓名不能為空',
'age.number' => '年齡必須為數(shù)字類型',
'age.between' => '年齡范圍1-120',
'email' => '郵箱格式不正確'
];
// 注意post后有個(gè)點(diǎn)
$data = input('post.');
$validate = new Validate($rules, $msg);
$res = $validate->check($data);
if(!$res){
echo $validate->getError();
}
鏈接MySQL數(shù)據(jù)庫
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 [
// 數(shù)據(jù)庫類型
'type' => 'mysql',
// 服務(wù)器地址
'hostname' => '127.0.0.1',
// 數(shù)據(jù)庫名
'database' => 'test',
// 用戶名
'username' => 'root',
// 密碼
'password' => '***',
... ...
index.php
use think\Db;
$res = Db::query('select * from user');
return $res;
總結(jié)
以上是生活随笔為你收集整理的request mysql 接口_TP5接口开发的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 青青河边草剧情介绍
- 下一篇: django和mysql写注册_Djan