thinkphp6:访问mysql数据库(thinkphp 6.0.9/php 8.0.14)

一,在.env中配置数据库

[DATABASE]
TYPE = mysql
HOSTNAME = 127.0.0.1
DATABASE = mediabank
USERNAME = root
PASSWORD = rootpassword
HOSTPORT = 3306
CHARSET = utf8
DEBUG = true

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,编写php代码:

1,配置数据库
config/database.php
<?php
 
return [
    // 默认使用的数据库连接配置
    'default'         => env('database.driver', 'mysql'),
 
    // 自定义时间查询规则
    'time_query_rule' => [],
 
    // 自动写入时间戳字段
    // true为自动识别类型 false关闭
    // 字符串则明确指定时间字段类型 支持 int timestamp datetime date
    'auto_timestamp'  => true,
 
    // 时间字段取出后的默认时间格式
    'datetime_format' => 'Y-m-d H:i:s',
 
    // 时间字段配置 配置格式:create_time,update_time
    'datetime_field'  => '',
 
    // 数据库连接配置信息
    'connections'     => [
        'mysql' => [
            // 数据库类型
            'type'            => env('database.type', 'mysql'),
            // 服务器地址
            'hostname'        => env('database.hostname', '127.0.0.1'),
            // 数据库名
            'database'        => env('database.database', ''),
            // 用户名
            'username'        => env('database.username', 'root'),
            // 密码
            'password'        => env('database.password', ''),
            // 端口
            'hostport'        => env('database.hostport', '3306'),
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8
            'charset'         => env('database.charset', 'utf8'),
            // 数据库表前缀
            'prefix'          => env('database.prefix', ''),
 
            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'     => false,
            // 读写分离后 主服务器数量
            'master_num'      => 1,
            // 指定从服务器序号
            'slave_no'        => '',
            // 是否严格检查字段是否存在
            'fields_strict'   => true,
            // 是否需要断线重连
            'break_reconnect' => false,
            // 监听SQL
            'trigger_sql'     => env('app_debug', true),
            // 开启字段缓存
            'fields_cache'    => false,
        ],
 
        // 更多的数据库配置信息
    ],
];
2,创建一个model:
liuhongdi@lhdpc:/data/php/admapi$ php think make:model Article
Model:app\model\Article created successfully. 
在model中添加代码:
<?php
declare (strict_types = 1);
 
namespace app\model;
 
use think\Model;
use think\facade\Db;
 
/**
* @mixin \think\Model
*/
class Article extends Model
{
    //类名与表名不一致时在这里指定数据表名
    protected $table = "media";
    //查询一条记录
    public function getOneMediaById($id){
        //查询一条记录时用find方法
        $result = Db::table("media")->where("id",$id)->find();
        return $result;
    }
    //查询多条记录
    public function getAllSaleMedia(){
        //查询一条记录时用find方法
        $result = Db::table("media")->where("isSale",1)->select();
        return $result;
    }
}
3,在controller中调用:
<?php
declare (strict_types = 1);
 
namespace app\controller;
 
use app\BaseController;
use app\result\Result;
use think\Request;
use think\facade\Cache;
use app\model\Article as ArticleModel;
 
class Article extends BaseController
{
    //查询一条media记录
    public function oneMedia() {
        $id = $this->request->param("id",0,"intval");
        if($id == 0){
            //return show(config("status.error"), "参数错误");
            return Result::Error(1,"参数错误");
        }
        $article = new ArticleModel();
        $row = $article->getOneMediaById($id);
 
        if (is_null($row)) {
            return Result::Error(1,"数据错误");
        } else {
            return Result::Success($row);
        }
    }
 
    //查询多条media记录
    public function allMedia() {
 
        $article = new ArticleModel();
        $rows = $article->getAllSaleMedia();
 
        if (sizeof($rows) == 0) {
            return Result::Error(1,"没有符合条件的数据");
        } else {
            return Result::Success($rows);
        }
    }
}

三,测试查询数据库的效果

1,能匹配到数据时:
访问:
http://192.168.219.6:8000/article/onemedia?id=1
返回:
2,数据不存在时:
访问:
http://192.168.219.6:8000/article/onemedia?id=5
返回:
3,访问多条数据:
访问:
http://192.168.219.6:8000/article/allmedia
返回:

四,查看thinkphp和php的版本:

php

root@lhdpc:~# php --version
PHP 8.0.14 (cli) (built: Dec 23 2021 11:52:42) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.14, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.14, Copyright (c), by Zend Technologies

thinkphp

root@lhdpc:~# cd /data/php/admapi/
root@lhdpc:/data/php/admapi# php think version
v6.0.9
原文地址:https://www.cnblogs.com/architectforest/p/15743061.html