码迷,mamicode.com
首页 > 数据库 > 详细

Yii2 HOW-TO(4):PDO连接数据库错误

时间:2018-09-27 14:21:33      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:pre   this   user   schema   enable   PHP代码   sha   class   51cto   

问题代码

1,控制器代码如下:

    public function actionIndex()
    {
        $query = Country::find();

        $pagination = new Pagination([
            ‘defaultPageSize‘ => 5,
            ‘totalCount‘ => $query->count()
        ]);

        $countries = $query->orderBy(‘name‘)
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render(‘index‘, [
            ‘countries‘ => $countries,
            ‘pagination‘ => $pagination,
        ]);
    }

2,数据库配置文件db.php代码如下:

<?php

return [
    ‘class‘ => ‘yii\db\Connection‘,
    ‘dsn‘ => ‘mysql:host=localhost;dbname=yii2basic‘,
    ‘username‘ => ‘root‘,
    ‘password‘ => ‘‘,
    ‘charset‘ => ‘utf8‘,

    // Schema cache options (for production environment)
    //‘enableSchemaCache‘ => true,
    //‘schemaCacheDuration‘ => 60,
    //‘schemaCache‘ => ‘cache‘,
];

3,问题截图:

技术分享图片

技术分享图片

解决办法

将PDO连接中的dsn的host由“localhost”改为“127.0.0.1”即可,打开文件DB.PHP,修改如下:

<?php

return [
    ‘class‘ => ‘yii\db\Connection‘,
    ‘dsn‘ => ‘mysql:host=127.0.0.1;dbname=yii2basic‘,
    ‘username‘ => ‘root‘,
    ‘password‘ => ‘‘,
    ‘charset‘ => ‘utf8‘,

    // Schema cache options (for production environment)
    //‘enableSchemaCache‘ => true,
    //‘schemaCacheDuration‘ => 60,
    //‘schemaCache‘ => ‘cache‘,
];

结果截图

技术分享图片

Yii2 HOW-TO(4):PDO连接数据库错误

标签:pre   this   user   schema   enable   PHP代码   sha   class   51cto   

原文地址:http://blog.51cto.com/zhuxianzhong/2286561

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!