XAMPPでCakePHP(4.x)を動かそうとして、DB接続でちょっとハマったのでメモです。
DB接続設定でエラー
CakePHPでは、DB接続設定はプロジェクトフォルダ配下の「config」ディレクトリに存在する「app.php」に設定します。そのため、DBの接続設定を「app.php」に追加しました。
ところが、以下の画像のようなエラーメッセージ「[1045]Access denied for user ’my_app’@’localhost’(using password:YES)」が表示されました。
はて?’my_app’なんてユーザ作ってないし、設定してないな?my_appユーザを作ってみたけど、NG、app.phpには設定を追加したけど、なぜ?と思い、再度設定ファイルを確認。すると、「app.php」のDB設定の箇所に以下のような記載がありました。
'Datasources' => [
/**
* These configurations should contain permanent settings used
* by all environments.
*
* The values in app_local.php will override any values set here
* and should be used for local and per-environment configurations.
*
* Environment variable based configurations can be loaded here or
* in app_local.php depending on the applications needs.
*/
これをみると「app_local.php」は、設定を上書きするよ~みたいなことが書いてありますね。
しっかり読まなかったのがいけないのですが、初心者にありがちなミスをしてしまいました。
ということで、「app_local.php」のDatasourcesの値を書き換え、上書き保存。
'Datasources' => [
'default' => [
'host' => 'localhost',
/*
* CakePHP will use the default DB port based on the driver selected
* MySQL on MAMP uses port 8889, MAMP users will want to uncomment
* the following line and set the port accordingly
*/
//'port' => 'non_standard_port_number',
'username' => 'my_app', // DB接続ユーザ
'password' => 'secret', // DB接続ユーザのパスワード
'database' => 'sampledb', // 作成済みのDB名
/**
* If not using the default 'public' schema with the PostgreSQL driver
* set it here.
*/
//'schema' => 'myapp',
/**
* You can use a DSN string to set the entire configuration
*/
'url' => env('DATABASE_URL', null),
],
これで無事にDBに接続することができました。



コメント