tp6教程

tp6

安装

下载:composer create-project topthink/think tp

安装多应用:composer require topthink/think-multi-app

修改目录(完成)

├─app 应用目录
│  ├─index              主应用
│  │  ├─controller      控制器目录
│  │  ├─model           模型目录
│  │  ├─view            视图目录
│  │  ├─config          配置目录
│  │  ├─route           路由目录
│  │  └─ ...            更多类库目录
│  │ 
│  ├─admin              后台应用
│  │  ├─controller      控制器目录
│  │  ├─model           模型目录
│  │  ├─view            视图目录
│  │  ├─config          配置目录
│  │  ├─route           路由目录
│  │  └─ ...            更多类库目录
│
├─public                WEB目录(对外访问目录)
│  ├─admin.php          后台入口文件
│  ├─index.php          入口文件
│  ├─router.php         快速测试文件
│  └─.htaccess          用于apache的重写
│
├─config                全局应用配置目录
├─runtime               运行时目录
│  ├─index              index应用运行时目录
│  └─admin              admin应用运行时目录

http,get,post设置头

‘Content-Type’: ‘application/json’

‘Content-Type’: ‘application/x-www-form-urlencoded’

命令

查看命令:php think

创建控制器
php think make:controller admin\controller\User
php think make:controller index\controller\User
创建模型make:model
php think make:model admin\model\User
php think make:model index\model\User
创建中间件make:middleware
php think make:middleware admin\middleware\Http
php think make:middleware index\middleware\Oauth2
如果使用了多应用模式,可以快速生成一个应用,例如生成demo应用的指令如下:
php think build demo

跨域

Route::group( function () {
    Route::get('user', 'user/index');
    Route::post('useradd', 'user/useradd');
    Route::delete('userdel', 'user/userdel');
})->allowCrossDomain([
    'Access-Control-Allow-Origin'        => 'http://localhost:8080',
    'Access-Control-Allow-Headers'       =>'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN',
    'Access-Control-Allow-Methods'       =>'GET, POST, PUT, DELETE',
    'Access-Control-Allow-Credentials'   => 'true'
]);

安装视图

composer require topthink/think-view

输出html

return View::fetch('index', [
    'name'  => 'ThinkPHP',
    'email' => 'thinkphp@qq.com'
]);

html输出

{$name}

数据库Db

使用需要引入use think\facade\Db;

不需要写表前缀

$list = Db::name('user')->where('id', 1)->find();

必须写表前缀

$list = Db::table('dade_user')->where('id', 1)->find();
插入,添加
Db::execute("insert into dade_order_goods(name,price,state,stock,items,richtext,dade) values ($name,$price,$state,$stock,$items,$richtext,$date)");

分页
$pageSize = (1-1)*10;
$list = Db::query("select * from dade_order_goods limit $pageSize,10");

根据id倒序order by id desc分页
$pageSize = (1-1)*10;
$list = Db::query("select * from dade_order_goods order by id desc limit $pageSize,10");
加条件
select * from dade_user_withdrawal where (state=2) order by id desc limit $pageSize,7

查总数count(*)
$count = Db::query("select count(id) from dade_order_goods");//总数数组
$length = ceil($count[0]['count(id)']/10);//总页数

删除
Db::execute("delete from dade_order_goods where id=$id");

修改
 Db::execute("update dade_order_goods set name=$name,price=$price where id=$id");
 
 一次写入100条
 Db::table('cdj_pindex_house')
 ->limit(100)
 ->insertAll($info);

模型

创建模型

php think make:model admin\model\User

//定义id
protected $pk = 'uid';

//数据库表
protected $name = 'user';
//数据库表这个需要写表前缀
protected $table = 'think_user';

引入use app\admin\model\User as Users;
查询
$list = User::where('status', 1)->limit(3)->order('id desc')->select();
查两列
$user = User::column('id,user');

添加
$user = User::create([
    'name'  =>  'thinkphp',
    'email' =>  'thinkphp@qq.com'
]);
批量添加
$user = User::create([
    'name'  =>  'thinkphp',
    'email' =>  'thinkphp@qq.com'
], 
['name', 'email']);

更新
User::where('id', 1)->update(['name' => 'thinkphp']);

删除
User::destroy(1);
支持批量删除多个数据
User::destroy([1,2,3]);

倒序查询

Users::order('id desc')->select();

查询多少条分页

$ids = $request->get('ids');
$list = Users::page($ids,10)->order('id desc')->select();
$page  = Users::count();
$length = ceil($page/10);
$listpage = [$list,$page,$length];
return json($listpage);
//统计查询出多少条
$page = Users::where('user', 'like', '%'.$search .'%')->select()->count();

模型关系查询一对多,一对一

正向

一对多
public function orsers()
{
    return $this->hasMany(Order::class,'store_id');
}
一对一
public function stores()
{
    return $this->hasOne(Store::class, 'store_id');
}

反向

public function stores()
{
    return $this->belongsTo(Store::class,'store_id');
}
//查询
$idsv = 1;
$list = Users::with('stores')->page($idsv,10)->order('id desc')->select();

合并在一个数组里查询

$list = Orders::withJoin(['stores'  => ['id', 'user']])->page($idsv,10)->order('id desc')->select();

模型创建修改时间戳转换

protected $type = [
   'tiem2'  =>  'timestamp:Y/m/d H:i:s',
];
protected $createTime = 'tiem';
protected $updateTime = 'tiem1';
protected $dateFormat = "Y-m-d H:i:s";

PHP写入文件excel

第一种
file_put_contents("excel/tests.xlsx", $shuj, FILE_APPEND);
第二种(写入一次w,追加写入a)
$file = fopen("excel/test1.xlsx","a");
fwrite($file,"数据");
fclose($file);

php获得当前时间

$userlevel['time'] = date('Y-m-d H:i:s');
$userlevel['time'] = time();
第二种写法
$t=time();
date("Y-m-d H:i:s",$t);
日期转时间戳
strtotime(date("Y-m-d H:i"));
//获得7天前时间
$stime = mktime(0,0,0,date('m'),date('d')-7,date('Y'))-1;
$time = date("Ymd",$stime);

接收iview上传图片

$file = $request->file('file');
$savename = \think\facade\Filesystem::disk('public')->putFile( 'topic', $file);
echo $savename;

php生成随机数

$code = rand(10000, 99999);

保存数组解码数组

// 写入数据库之前
$staff_serialize = serialize($staff);            // 序列化成字符串
$staff_json = json_encode($staff);               // JSON编码数组成字符串

// 读取数据库后
$staff_restore = unserialize($staff_serialize);  // 反序列化成数组
$staff_dejson = json_decode($staff_json, true);  // JSON解码成数组

数组追加

$list = [$goodsid,$result];
$items = unserialize($order[0]['item']);
$itemss = array_merge($items,$list);

结果[3, "可以是的11111", 3, "可以是的11111", 3, "可以是的11111", 5, "可以是的1111111"]
0: 3
1: "可以是的11111"
2: 3
3: "可以是的11111"
4: 3
5: "可以是的11111"
6: 5
7: "可以是的1111111"

理想二维追加

$list = [[$goodsid,$result]];
$items = unserialize($order[0]['item']);
$itemss = array_merge_recursive($items,$list);

结果[[5, "可以是的1111111"], [5, "可以是的1111111"], [2, "可以是的"], [2, "可以是的"], [2, "可以是的"], [2, "可以是的"]]
0: [5, "可以是的1111111"]
1: [5, "可以是的1111111"]
2: [2, "可以是的"]
3: [2, "可以是的"]
4: [2, "可以是的"]
5: [2, "可以是的"]

获得url

$_SERVER[‘HTTP_HOST’]

php跳转

header("Location:".$url);

微信授权获得网站输出

$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$weix = file_get_contents($url);//获得网页输出

redis缓存,缓存

use think\facade\Cache;//引入

$security = $user."_security";
Cache::set($security, $users[0]['jurisdiction'],36000);//缓存权限
$securitys = Cache::get($security);//查

php拆分成数组

$Plain = “aaa|666|777”;

l i s t = e x p l o d e ( ′ ∣ ′ , list = explode('|', list=explode(,Plain);

微信发送消息推送

public function template($id)
{
    $user = User::where('id',$id)->value('openid');//微信openid
    $url = $_SERVER['HTTP_HOST'];
    $wxurl = 'https://api.weixin.qq.com/cgi-bin/token/template/send?access_token=ACCESS_TOKEN';
    $weixin = Weixin::where('id',1)->select();
    $appid = $weixin[0]['appid'];//公众号appid
    $secret = $weixin[0]['appsecret'];//公众号appsecret
    //获得access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
    $weix = file_get_contents($url);//获得网页输出
    $obj=json_decode($weix,true );//解码
    $access_token= $obj['access_token'];//网页授权接口调用凭证
    //发送模板消息
    $fasuerl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
    $data = array(
        "touser"=>$user,
        "template_id"=>"2GSNHCC4xOrz9p9fqmKLbUwknwVa1iZnClqzbQb5xhw",
        "data" => array(
            "first" => array(
                "value"=>"咨询通知",
                "color"=>"#173177"
            ),
            "keyword1" => array(
                "value"=>"巧克力!",
                "color"=>"#000000"
            ),
            "keyword2" => array(
                "value"=>"巧克力!",
                "color"=>"#000000"
            ),
            "remark" => array(
                "value"=>"巧克力!",
                "color"=>"#000000"
            ),
        )
    );
    $params = json_encode($data);
    $res=$this->curl_post($fasuerl,$params);
    print_r($res);
}
//发送post请求
function curl_post($url , $data=array()){
    $ch = curl_init();//创建curl请求
    curl_setopt($ch, CURLOPT_URL,$url); //设置发送数据的网址
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设置有返回值,0,直接显示
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); //禁用证书验证
    curl_setopt($ch, CURLOPT_POST, 1);//post方法请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//post请求发送的数据包
    $data = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($data,true); //将json数据转成数组
    return $data;
}

微信注册

//微信信息,跳转授权
public function index()
{
    $weixin = wx::where('id',1)->select();
    $APPID = '';
    $url = '';
    $scope='snsapi_userinfo';
    foreach ($weixin as $item){
        $APPID = $item['appid'];
        $list[0]['appid'] = $item['appid'];
        $list[0]['appsecret'] = $item['appsecret'];
        $list[0]['encodingaeskey'] = $item['encodingaeskey'];
        $url = $_SERVER['HTTP_HOST'];
        $list[0]['url'] = $url."/".$item['url'];
        $url = 'http://'.$url."/".$item['url'];
        $list[0]['token'] = $item['token'];
    }
    $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$APPID."&redirect_uri=".urlencode($url)."&response_type=code&scope=".$scope."&state=STATE#wechat_redirect";
    $liste = [$url];
    return json($liste);
}
//获得用户信息,跳转返回可以获得信息
public function weixiname(Request $request){
    $code = $request->get('code');
    $state = $request->get('state');
    $weixin = wx::where('id',1)->select();
    $appid = $weixin[0]['appid'];
    $secret = $weixin[0]['appsecret'];
    //获得openid
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
    $weix = file_get_contents($url);//获得网页输出
    $obj=json_decode($weix,true );//解码
    $accesstoken= $obj['access_token'];//网页授权接口调用凭证
    $openid = $obj['openid'];//openid
    //获得用户信息
    $urlname = "https://api.weixin.qq.com/sns/userinfo?access_token=$accesstoken&openid=$openid&lang=zh_CN";
    $weixs = file_get_contents($urlname);
    $objs=json_decode($weixs,true );//解码
    $user['openid'] = $objs['openid'];//openid
    $user['user'] = $objs['nickname'];//微信名称
    $user['province'] = $objs['province'];//用户个人资料填写的省份
    $user['city'] = $objs['city'];//用户个人资料填写的城市
    $user['img'] = $objs['headimgurl'];//头像,用户更换头像时,失效
    //登陆
    if($objs['openid']){
        $users = User::where('openid',$objs['openid'])->value('openid');
        if(empty($users)){
            //第一次
            $user['level_id'] = 1;
            $user['level'] = "普通会员";
            $user['time'] = date('Y-m-d H:i:s');//加入时间
            User::create($user);
            $list = User::where('openid',$objs['openid'])->select();
            $user_id = $list[0]['id'];
            $user_user = $list[0]['user'];
            $openid = $list[0]['openid'];
            $img = $list[0]['img'];
            $url = "http://localhost:8080/#/loginwx?user_id=$user_id&user_user=$user_user&openid=$openid&member=1&img=$img";
            header("Location:".$url);
        }else{
            //已存在用户
            $list = User::where('openid',$objs['openid'])->select();
            //更新图片
            if($list[0]['img'] == $objs['headimgurl']){

            }else{
                $user_img = $objs['headimgurl'];
                User::where('openid', $objs['openid'])->update(['img' => $user_img]);
            }
            $user_id = $list[0]['id'];
            $user_user = $list[0]['user'];
            $openid = $list[0]['openid'];
            $img = $list[0]['img'];
            $store = Store::where('user_id',$user_id)->select();
            if(empty($store[0]['id'])){
                $expert = Expert::where('user_id',$user_id)->select();
                if(empty($expert[0]['id'])){
                    //用户
                    $url = "http://localhost:8080/#/loginwx?user_id=$user_id&user_user=$user_user&openid=$openid&member=1&img=$img";
                    header("Location:".$url);
                }else{
                    //专家
                    $expert_id = $expert[0]['id'];
                    $region = $expert[0]['region'];//南方。还是北方
                    $expert_name = $expert[0]['name'];//专家姓名
                    $url = "http://localhost:8080/#/loginwx?user_id=$user_id&user_user=$user_user&openid=$openid&member=3&img=$img&expert_id=$expert_id&region=$region&expert_name=$expert_name";
                    header("Location:".$url);
                }
            }else{
                //加盟店或省代
                $store_id = $store[0]['id'];
                $store_level = $store[0]['level'];//门店级别,是省代,还是门店
                $store_user = $store[0]['user'];//门店名称
                $url = "http://localhost:8080/#/loginwx?user_id=$user_id&user_user=$user_user&openid=$openid&member=2&img=$img&store_id=$store_id&store_level=$store_level&store_user=$store_user";
                header("Location:".$url);
            }
        }
    }
}

//判断用户存在不存在,级别是否变动
public function weixinpd(Request $request){
    $id = $request->get('id');
    $jib = $request->get('jib');
    if($jib == 1){
        $list = User::where('id',$id)->select();
        $store = Store::where('user_id',$id)->select();
        $expert = Expert::where('user_id',$id)->select();
        if(empty($store[0]['id'])){

        }else{
            return json(1);
        }
        if(empty($expert[0]['id'])){

        }else{
            return json(1);
        }
        if(empty($list[0]['id'])){
            return json(1);
        }else{
            return json(2);
        }
    }
    if($jib == 2){
        $store = Store::where('id',$id)->select();
        $user_id = $request->get('user_id');
        $store_level = $request->get('store_level');
        if(empty($store[0]['id'])){
            return json(1);
        }else{
            if($store[0]['level'] != $store_level){
                return json(1);
            }
            if($store[0]['user_id'] == $user_id){
                return json(2);
            }else{
                return json(1);
            }
        }
    }
    if($jib == 3){
        $user_id = $request->get('user_id');
        $expert = Expert::where('id',$id)->select();
        if(empty($expert[0]['id'])){
            return json(1);
        }else{
            if($expert[0]['user_id'] == $user_id){
                return json(2);
            }else{
                return json(1);
            }
        }
    }
}

原生连接数据库mysql

// 创建连接
    $conn = new mysqli($servername, $username, $password,'sql_322_zgh_iotc');
    // 检测连接
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }
    $sql = "update `ims_ewei_shop_order` set status=2,mercdttm='{$MercDtTm}',acqssn='{$AcqSsn}',settdate='{$SettDate}' where termtsn='{$TermSsn}'";
//    echo $sql;
    $res = mysqli_query($conn,$sql);
    mysqli_affected_rows($conn);
    mysqli_close($conn);

数组降序,升序

$guys = array(
    array('name'=>'jake', 'score'=>80, 'grade' =>'A'),
    array('name'=>'jina', 'score'=>70, 'grade'=>'A'),
    array('name'=>'john', 'score'=>70, 'grade' =>'A'),
    array('name'=>'ben', 'score'=>20, 'grade'=>'B')
);
//例如我们想按成绩倒序排列,如果成绩相同就按名字的升序排列。*
//这时我们就需要根据$guys的顺序多弄两个数组出来:*
$scores = array(80,70,70,20);
$names = array('jake','jina','john','ben');
//然后,排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
array_multisort($scores, SORT_DESC, $names, $guys);

//测试成功
$list = 二维数组;
$scores = array();
$names = array();
foreach ($list as $key=>$it){
	$scores[$key] =  $it['mobile'];
	$names[$key] = $it['id'];
} 
array_multisort($scores, SORT_DESC, $names, $list);
直接输出$list就可以

二维数组转一维数组,转字符串

//$list1是二维数组
$array = array_column($list1, 'jurisdiction_id');//转一维
$implode = implode(",",$array);//转字符串逗号隔开

文件锁定一个一个来

$file = 'static/temp.txt';//文件路径
$fp = fopen($file,'a');//打开文件
//排队一个一个来,设定
if(flock($fp,LOCK_EX)){
    for($i = 0;$i < 5;$i++)
    {
        fwrite($fp, "11111111n");
        sleep(1);
    }
    flock($fp,LOCK_UN);//释放设定
}
fclose($fp);//关闭文件,释放

下载phpexcel操作

tp6安装phpexcel,进入这个项目运行
composer require phpoffice/phpexcel

读取excel文件内容保存数据库
引入use PHPExcel_IOFactory;
			//$path1路径
			$objPHPExcel = PHPExcel_IOFactory::load($path1);
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $k = 0;
            $info = array();
            $ids = 0;
            for($j=1;$j<=$highestRow;$j++)
            {
                $a = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//获取A列的值
                $b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取B列的值
                $info[$ids]['a'] = $a;
                $info[$ids]['b'] = $b;
                $ids++;
            }
            return json($info);

数组合并array_merge

$sfx = Db::query("select id,name as label from cdj_pindex_house_charge where pindex_id=$id and type=$type and fixed=2");
        $sfx1 = Db::query("select company_id from cdj_pindex where id=$id");
        $cid = $sfx1[0]['company_id'];
        $sfx2 = Db::query("select id,name as label from cdj_pindex_house_charge where company_id=$cid and type=$type and fixed=1");
        
$sfx = array_merge($sfx,$sfx2);

获得一年12月

$yuef = [];
$currentTime = time();
$cyear = floor(date("Y",$currentTime));
$cMonth = floor(date("1",$currentTime));
for($i=0;$i<12;$i++){
    $nMonth = $cMonth+$i;
    $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;//年
    $nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;//月
    $date = $cyear."-".$nMonth."-1";
    $firstday = date('Y-m-01', strtotime($date));//当月第一天
    $lastday = date('Y-m-t', strtotime($date));//当月最后阳台
    $string = $cyear."年".$nMonth."月".$firstday."日";
    $string1 = $cyear."年".$nMonth."月".$lastday."日";
    $yuef[]=[$string,$string1];
}

域名将反斜杆转为正斜杠

将反斜杆转为正斜杠
str_replace("\\",'/',$info->getSaveName()), *//将反斜杆转为正斜杠*

获得域名后面的路由

$url = parse_url($request->baseUrl());

门面

<?php
namespace app\common;
use think\Facade;
use think\facade\App;
use app\admin\model\AdministratorsLog as log;

class Facades extends Facade
{
    public static function log($list){
        //写日记
        $log['company_id'] = $list['company_id'];//组织
        $log['name'] = $list['name'];//账号
        $log['caozuo'] = $list['caozuo'];//操作类型
        $log['caozuoxiangqin'] = $list['caozuoxiangqin'];//操作内容
        $log['date'] =time();//操作时间
        log::create($log);
        return 1;
    }
        //引入use app\common\Facades;//使用Facades::log(参数);
        //写日记模板
        //$listLog['company_id'] = $request->userList['company_id'];//组织
        //$listLog['name'] = $request->userList['user'];//登录账号
        //$listLog['caozuo'] = "架构";//操作类型
        //$listLog['caozuoxiangqin'] = "$baoc"."收费项,名称:".$dates["name"].",id:".$id.$idc;//操作内容
        //Facades::log($listLog);
}

一维数组合并,号隔开

$userJArr = implode(',',$userJArr);
逗号分割
$list[0]['pindex_id'] = explode(",",$pindex_id);
获得一维数组长度
count($length);

url反斜杠转正斜杠

$date['carousel'] = str_replace("\\",'/',$date['carousel']);

视图

 安装
 composer require topthink/think-view

 使用
 public function index()
 {
     View::assign([
         'name'  => 'ThinkPHP',
         'email' => 'thinkphp@qq.com'
     ]);
     return View::fetch('index');
 }
 
 在view新建
 index/index.html
 
 模板使用
 新建common/haeder.html
 在index中引入
 {include file="common/haeder"/}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大得369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值