>  기사  >  PHP 프레임워크  >  yii2가 데이터베이스에 연결하지 못했습니다.

yii2가 데이터베이스에 연결하지 못했습니다.

王林
王林원래의
2020-02-26 15:38:002857검색

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 Framework)

2.

<?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 호스트를 "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;,
];

For 더 많은 프로그래밍 관련 내용은 PHP 중국어 홈페이지 프로그래밍 입문 칼럼을 주목해주세요!

위 내용은 yii2가 데이터베이스에 연결하지 못했습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.