ThinkPHP5连接数据库

ThinkPHP5连接数据库:

方法一、配置文件定义
a、配置文件目录
C:\AppServ\www\tp5\application\database.php
b、如何配置
return [
    // 数据库类型
    'type'            => 'mysql',
    // 服务器地址
    'hostname'        => '127.0.0.1',
    // 数据库名
    'database'        => 'yest',
    // 用户名
    'username'        => 'root',
    // 密码
    'password'        => '123456',
    // 端口
    'hostport'        => '3306',
];
c、如何使用
// 实例化系统数据库类
$DB=new Db;
// 查询数据
$data=$DB::table("user")->select();
// 使用sql语句
$data=$DB::query("select * from user");

方法二、方法配置(在index.php中)
1、使用数组
$Db=Db::connect([
// 数据库类型
'type'            => 'mysql',
// 服务器地址
'hostname'        => '127.0.0.1',
// 数据库名
'database'        => 'test',
// 用户名
'username'        => 'root',
// 密码
'password'        => '123456',
// 端口
'hostport'        => '3306',
]);
2、使用字符串
$Db=Db::connect("mysql://root:[email protected]:3306/test#utf8");
// 数据库类型://用户名:密码@数据库地址:数据库端口/数据库名#字符集
3、如何使用
$data=$Db->table("user")->select();

方法三、模型类定义
1、创建数据模型
a、命令行创建
1、切换到项目目录
2、执行命令
php think make:model app\index\model\User
b、手动创建
1、打开数据模型目录
C:\AppServ\www\tp5\application\index\model
2、在目录下新建 文件 User.php
3、在文件中书写代码
namespace app\index\model;

use think\Model;

class User extends Model
{
    //
}
2、如何设置
class User extends Model
{
    // 使用数组配置链接数据库
    protected $connection=[
    // 数据库类型
    'type'            => 'mysql',
    // 服务器地址
    'hostname'        => '127.0.0.1',
    // 数据库名
    'database'        => 'test',
    // 用户名
    'username'        => 'root',
    // 密码
    'password'        => '123456',
    // 端口
    'hostport'        => '3306',
    ];
    // 使用字符串配置链接数据库
    protected $connection="mysql://root:[email protected]:3306/test#utf8";
}

3、如何控制器中使用
$user=new \app\index\model\User();
// 查询所有的数据
dump($user::all());

猜你喜欢

转载自blog.csdn.net/shaoyanlun/article/details/80540370