First of all, let’s take a look at the problem code:
1. The controller code is as follows:
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, ]); }
(Recommended tutorial: yii framework )
2. The code of the database configuration file db.php is as follows:
<?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', ];
Solution:
Change the host of the dsn in the PDO connection from "localhost" Just "127.0.0.1", open the file DB.PHP, and modify it as follows:
<?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', ];
For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!
The above is the detailed content of yii2 failed to connect to database. For more information, please follow other related articles on the PHP Chinese website!