广告:宝塔Linux面板高效运维的服务器管理软件 点击【 https://www.bt.cn/p/uNLv1L 】立即购买
首先,先来看一下问题代码:
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 [ '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',];登录后复制
解决方法:
将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',];登录后复制
更多编程相关内容,请关注9543建站博客编程入门栏目!
以上就是yii2连接数据库失败的详细内容,更多请关注9543建站博客其它相关文章!
发表评论