Yii2 HOW-TO(4):PDO連接數據庫錯誤
阿新 • • 發佈:2018-09-27
yii fun nag dsn roo oot order ext -o 問題代碼
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, ]); }
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‘, ];
3,問題截圖:
解決辦法
將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‘, ];
結果截圖
Yii2 HOW-TO(4):PDO連接數據庫錯誤