A PHP class to read Microsoft Access Database

A friend of mine recently asked me to help out building a data warehouse based on some Access database files. Here is a PHP class that I created to read database record from Access.

class DataMdb {
	private $conn;

	function __construct($mdbFile) {
		// Set up the connection
		if (!$this->conn = new COM("ADODB.Connection")) {
			exit("Unable to create an ADODB connection");
		}
		$strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath($mdbFile);
		try {
			$this->conn->open($strConn);
		} catch (Exception $e) {
			exit("Caught exception: " . $e->getMessage());
		}
	}
	
	function getAll($sql) {
		$result = array();
		try {
			$rs = $this->conn->execute($sql);

			if (!$rs->EOF) {
				$rs->MoveFirst();
				$fieldCnt = $rs->Fields->Count();

				while (!$rs->EOF) {
					$row = array();
					for ($i=0; $i<$fieldCnt; $i++) {
						$row[$rs->Fields($i)->name] = $rs->Fields($i)->value;
					}
					$result[] = $row;
					$rs->MoveNext();
				}
			}			
			$rs->close();
			
		} catch (Exception $e) {
			exit("Caught exception: " . $e->getTraceAsString());
		}

		return $result;
	}

	function disconnect() {
		$this->conn->close();
	}
}
This entry was posted in PHP development. Bookmark the permalink.