Home > PHP Framework > YII > yii2 failed to connect to database

yii2 failed to connect to database

王林
Release: 2020-02-26 15:38:00
Original
2978 people have browsed it

yii2 failed to connect to database

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,
        ]);
    }
Copy after login

(Recommended tutorial: yii framework )

2. The code of the database configuration file db.php is as follows:

<?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;,
];
Copy after login

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 [
    &#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;,
];
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template