首先,先來看看問題程式碼:
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', ];
更多程式相關內容,請關注php中文網程式入門欄位!
以上是yii2連線資料庫失敗的詳細內容。更多資訊請關注PHP中文網其他相關文章!