ここでは、PDO を利用して MySQL へ接続や切断、およびトンランザクション管理を行う基本的なデータベース接続用クラスのサンプルコードを掲載しています。
スポンサーリンク
MySQL 接続用クラスのサンプル
MySQL 接続およびトランザクション管理を行うクラスのサンプルです。基本的な操作(クエリの発行は除く)は網羅していると思います。サンプル中のコメントも参照ください。
/** * サンプル:DB接続およびトランザクション管理 */ class Sample_Adapter { /** * MySQL接続リソース */ protected $_connection = null; /** * コンストラクタ */ public function __construct() { } /* * デストラクタ:データベースに接続中の場合は切断する */ public function __destruct() { $this->close(); } /* * データベースに接続する */ public function connect() { // 既に接続している場合はリターン if($this->isConnected()) { return; } // DSNの作成 $db_name = 'testdb'; $db_host = 'localhost'; $db_port = 3306; $dsn = 'mysql:dbname=' . $db_name . ';host=' . $db_host . ';port=' . $db_port; try { // データベースに接続する $this->_connection = new PDO($dsn, 'user_name', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET 'utf8'") ); } catch (PDOException $e) { // エラーコードおよびメッセージを取得するには以下のように取得する // $e->getMessage(), (int)$e->getCode() throw $e; } } /** * 既に接続しているか確認する */ public function isConnected() { return ((bool) ($this->_connection instanceof PDO)); } /* * データベールから切断する */ public function close() { $this->_connection = null; } /** * トランザクションを開始する */ public function beginTransaction() { $this->connect(); $this->_connection->beginTransaction(); return $this; } /** * コミットする */ public function commit() { $this->connect(); $this->_connection->commit(); return $this; } /* * ロールバックする */ public function rollback() { $this->connect(); $this->_connection->rollBack(); return $this; } /** * MySQL 接続リソースを返す */ public function getConnection() { $this->connect(); return $this->_connection; } }
コミットやロールバックでの再接続処理に意味はあるのだろうか。。。そんな時はスクリプトがバグってるような気もしたりしなかったり。。。