首頁 >php框架 >YII >yii2連線資料庫失敗

yii2連線資料庫失敗

王林
王林原創
2020-02-26 15:38:002944瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn