せかいや

いまいるここを、おもしろく http://sekai-in-the-box.appspot.com/

【symfony2】【PHP】could not find driver エラー

データベースと Doctrineを参考にMySQLへの接続にチャレンジ

Doctrine からデータベースを作成してみましょう。次のコマンドを実行してください。
php app/console doctrine:database:create

実行してみると、ドライバーが見つからないとのエラー↓

C:\xampp\htdocs\Symfony>C:\xampp\php\php.exe app/console doctrine:database:create
Could not create database for connection named `test_project`
could not find driver

phpinfo()で確認すると、pdo_mysqlは定義できています。おかしいな。


■解決

1)設定ファイルはparameters.yml

ガイドにはこう書いてありますが↓

データベース接続の設定を行う必要があります。慣例として、通常は app/config/parameters.ini で設定を行います。

これは古い(?)情報みたい。
parameters.iniは初期フォルダに存在せず、怪しいなと思いながら作成したら、果たして読み込めていない様子。
parameters.iniは読み込まれず、最初からデモに存在しているparameters.ymlに情報を記載する必要がある。
 ⇒parameters.iniとparameters.ymlが両方存在していると、ymlが勝つのか?

2)DB接続の公開鍵を取得する

parameters.ymlのデフォルトはこの状態です↓

parameters:
database_driver: pdo_mysql
database_host: 127.0.0.1
database_port: ~
database_name: symfony
database_user: root
database_password: ~
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: ~
mailer_password: ~
locale: en
secret: ThisTokenIsNotSoSecretChangeIt

この中のdatabase_name やdatabase_user、database_passwordは変更したのですが、secret属性も変更する必要があります。
なんでこのあたりガイドに書いてないの><?

DB接続の公開鍵取得方法:
http://localhost/Symfony/web/app_dev.php/ からページ真ん中の「configure」をクリック。
ここから接続したいDBの設定をすることでsecretキーを発行できます。

■Tips
DB接続をphpコマンドで実行する前に、MySQLコマンドで接続を試した方が、障害切り分けが簡単になります。

実行コマンド

# mysql -u syuser -p

実行結果

Enter password: ******
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 5.5.16 MySQL Community Server (GPL)

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.