首页 > php框架 > YII > yii2连接数据库失败

yii2连接数据库失败

王林
发布: 2020-02-26 15:38:00
原创
2927 人浏览过

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; => &#39;yii\db\Connection&#39;,
    &#39;dsn&#39; => &#39;mysql:host=localhost;dbname=yii2basic&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;&#39;,
    &#39;charset&#39; => &#39;utf8&#39;,
 
    // Schema cache options (for production environment)
    //&#39;enableSchemaCache&#39; => true,
    //&#39;schemaCacheDuration&#39; => 60,
    //&#39;schemaCache&#39; => &#39;cache&#39;,
];
登录后复制

解决方法:

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

<?php
 
return [
    &#39;class&#39; => &#39;yii\db\Connection&#39;,
    &#39;dsn&#39; => &#39;mysql:host=127.0.0.1;dbname=yii2basic&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;&#39;,
    &#39;charset&#39; => &#39;utf8&#39;,
 
    // Schema cache options (for production environment)
    //&#39;enableSchemaCache&#39; => true,
    //&#39;schemaCacheDuration&#39; => 60,
    //&#39;schemaCache&#39; => &#39;cache&#39;,
];
登录后复制

更多编程相关内容,请关注php中文网编程入门栏目!

以上是yii2连接数据库失败的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板