yii2连接数据库失败

yii2连接数据库失败

首先,先来看一下问题代码:

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,         ]);     }

(推荐教程:yii框架

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

<?php   return [     &#39;class&#39; => 'YIIdbConnection',     'dsn' =&gt; 'mysql:host=localhost;dbname=yii2basic',     'username' =&gt; 'root',     'password' =&gt; '',     'charset' =&gt; 'utf8',       // Schema cache options (for production environment)     //'enableSchemaCache' =&gt; true,     //'schemaCacheDuration' =&gt; 60,     //'schemaCache' =&gt; 'cache', ];

解决方法:

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

<?php   return [     &#39;class&#39; => 'yiidbConnection',     'dsn' =&gt; 'mysql:host=127.0.0.1;dbname=yii2basic',     'username' =&gt; 'root',     'password' =&gt; '',     'charset' =&gt; 'utf8',       // Schema cache options (for production environment)     //'enableSchemaCache' =&gt; true,     //'schemaCacheDuration' =&gt; 60,     //'schemaCache' =&gt; 'cache', ];

更多编程相关内容,请关注php中文网yii框架栏目!

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享