edo1z blog

プログラミングなどに関するブログです

cakephp2 - database.phpの情報でmysqlのpdoで接続する

cakephp2で、database.phpの情報でmysqlのpdoで接続する方法。

下記で、database.phpで設定している内容を取得できる。

include_once APP.'Config'.DS.'database.php';
if(class_exists('DATABASE_CONFIG'))
{
    $this->db_config = new DATABASE_CONFIG();
}

下記で、dbに接続できる。

private function connect_db()
{
    try
    {
        $this->pdo = new PDO('mysql:host='.$this->db_config->default['host'].';dbname='.
                             $this->db_config->default['database'].';charset=utf8',
                             $this->db_config->default['login'], $this->db_config->default['password']);
    }
    catch(PDOException $e)
    {
        exit('データベース接続失敗。'.$e->getMessage());
    }
}

下記で、データベースに存在するテーブルをすべて削除できる。

private function drop_tables()
{
    try
    {
        $stmt = $this->pdo->query('SHOW TABLES');
        $tables = $stmt->fetchAll();
        foreach($tables as $tbl)
        {
            $this->pdo->exec('drop table if exists '.$tbl[0]);
        }
    }
    catch(PDOException $e)
    {
        exit('テーブル削除失敗。'.$e->getMessage());
    }
}

下記で、データベースにsqlをインポートできる。

private function import_sql()
{
    $sql = $this->get_sql();
    try
    {
        return $this->pdo->exec($sql);
    }
    catch(PDOException $e)
    {
        exit('sqlインポート失敗。'.$e->getMessage());
    }
}
private function get_sql()
{
    try
    {
        return file_get_contents($this->sql_path);
    }
    catch(Exception $e)
    {
        exit('sqlファイル取得失敗。'.$e->getMessage());
    }
}