Location: PHPKode > scripts > mysql2object > mysql2object/database.class.php
<?

require_once('datasource.class.php');
require_once('table.class.php');

/**
 * Database Class - part of MySQL2Object set of classes
 *
 * @author Arkadiusz Mali&#324;ski <hide@address.com>
 * @package mysql2object
 */
class Database {
	
	/**
	 * data source from DB class
	 *
	 * @var DB
	 */
	private $_db = null;
	
	/**
	 * array of Tables
	 *
	 * @var array
	 */
	private $_arTables = array();
	
	/**
	 * array of 'check loaded' values
	 *
	 * @var array
	 */
	private $_tablesLoaded;
	
	/**
	 * database name
	 *
	 * @var string
	 */
	private $_name;

	
	/**
	 * Constructor loads all table names.
	 *
	 * @param DB $datasource
	 */
	public function __construct(DB $datasource) {
		$this->_db =& $datasource;
		
		$dbname = $this->_db->query('SELECT DATABASE() AS dbname');
		$this->_name = $dbname[0]['dbname'];
		
		$_tbl = $this->_db->query('SHOW TABLES');
		foreach ($_tbl as $_tables) {
			$this->_tablesLoaded[$_tables[0]] = false;
		}
	}

	
	/**
	 * Returns database name
	 *
	 * @return string
	 */
	public function __toString() {
		return $this->_name;
	}

	
	/**
	 * Handling tables calls
	 *
	 * @param string $func
	 * @return Table
	 */
	public function __get($func) {
		if(key_exists($func, $this->_tablesLoaded)) {
			if(!$this->_tablesLoaded[$func]) {
				$this->loadTable($func);
				$this->_tablesLoaded[$func] = true;
				return $this->_arTables[$func];
			} else {
				return $this->_arTables[$func];
			}
		} else {
			switch (strtolower($func)) {
				case 'all':
					return array_keys($this->_tablesLoaded);
					break;
				default:
					throw new DatabaseException('Unknown table name "'.$func.'"');
					break;
			}
		}
		
	}
	
	
	/**
	 * Load and store definition and data of selected table
	 *
	 * @param string $tablename
	 */
	private function loadTable($tablename) {
		$tbl = array();
		$tbl['name'] = $tablename;
		$tbl['colDescription'] = $this->_db->query('DESCRIBE '.$tbl['name']);
		$tbl['tblDescription'] = $this->_db->query('SHOW TABLE STATUS LIKE "'.$tbl['name'].'"');
		$tbls_values = $this->_db->query('SELECT * FROM '.$tbl['name']);
		$columns = array();
		foreach ($tbls_values as $x) {
			for($i=0; $i<(count($x)/2);$i++) {
				$columns[$i][] = $x[$i];
			}
		}
		$tbl = array_merge($tbl, array('colValues'=>$columns));
		$this->addTable(new Table($tbl, $this->_db));
	}


	/**
	 * Add table to array
	 *
	 * @param Table $table
	 */
	private function addTable(Table $table) {
		$this->_arTables[$table->__toString()] = $table;
	}
	
}

class DatabaseException extends Exception {}

?>
Return current item: mysql2object