Location: PHPKode > projects > Network Configuration Store > NCS-3.0.2/wwwroot/inc/CSDatabase.class.php
<?php

require_once('MDB2.php');

define('CSDB_VERSION', 4); // 3.0-beta2

class CSDatabase
{
	private $dsn;
	private $db;

	public function __construct($server, $usernm, $passwd, $dbase, $port=3306, $fetchmode=MDB2_FETCHMODE_ASSOC)
	{
		// Adding :port to the hostspec seems to break MDB2...
		$this->dsn = array(
			'phptype'  => 'mysqli',
			'username' => $usernm,
			'password' => $passwd,
			'hostspec' => $server,
			'database' => $dbase
		);

		$this->db =& MDB2::factory($this->dsn);

		if (MDB2::isError($this->db))
			throw new Exception('Cannot connect to database: '.MDB2::errorMessage($this->db));

		// Set our MDB2 fetch mode...
		$this->db->setFetchMode($fetchmode);
	}
	public function __destruct()
	{
		if ($this->db && !MDB2::isError($this->db))
		{
			$this->db->disconnect();
			unset($this->db);
		}
	}

	// CheckVersion
	//	Checks the version of our database matches CSDB_VERSION
	//	Throws exception on failure.
	//
	public function CheckVersion()
	{
		return true;
	}

	// ExecuteQuery
	//	Prepares a statement handle and executes the query
	//
	public function &ExecuteQuery($query, $params, $fetchmode=MDB2_FETCHMODE_ASSOC)
	{
		if (empty($query))
			throw new Exception('CSDatabase::ExecuteQuery() with no query string');
		if (!is_array($params))
			$params = array($params);

		//
		// Let's try and see what prepare mode we need
		//
		if (!strncasecmp($query, 'SELECT', 6))
			$prepmode = MDB2_PREPARE_RESULT;
		else
			$prepmode = MDB2_PREPARE_MANIP;

		//
		// Now let's try and work out our parameter types
		// I don't think we'll use anything other than string, int and bool.
		//
		$types = array();
		foreach($params as $p)
		{
			if (is_string($p))
				$types[] = 'text';
			elseif (is_integer($p))
				$types[] = 'integer';
			elseif (is_bool($p))
				$types[] = 'boolean';
			else
				throw new Exception('CSDatabase::ExecuteQuery() encountered an unsupported parameter type.');
		}

		// Build the statement!
		$st = $this->db->prepare($query, $types, $prepmode);
		if (MDB2::isError($st))
			throw new Exception('Could not prepare query: '.$st->getMessage().' ['.$res->getUserInfo().']');

		// Execute it...
		$res = $st->execute($params);
		if (MDB2::isError($res))
			throw new Exception('Could not execute query: '.$res->getMessage().' ['.$res->getUserInfo().']');

		$st->free();

		// This is either an MDB2_Result or an Integer
		return $res;
	}

	private function &Read($query, $params, $limit=0, $offset=0)
	{
		if ($limit > 0)
			$this->db->setLimit($limit, $offset);

		$res =& $this->ExecuteQuery($query, $params);
		if (!MDB2::isResult($res))
			throw new Exception('CSDatabase::Read(): ExecuteQuery() did not return a valid MDB2_Result object');

		return $res;
	}

	private function Write($query, $params)
	{
		$res =& $this->ExecuteQuery($query, $params);
		if (!is_integer($res))
			throw new Exception('CSDatabase::Write(): ExecuteQuery() did not return an integer');

		return $res;
	}

	// GetOneRecord()
	//	Execute a query, and return a single record
	//
	public function GetOneRecord($query, $params=array())
	{
		$res =& $this->Read($query, $params, 1);
		$row = $res->fetchRow();
		$res->free();

		return $row;
	}

	// GetOneField()
	//	Execute a query, and return the single field parameter
	//
	public function GetOneField($query, $field, $params=array())
	{
		$res = $this->GetOneRecord($query, $params);

		// If we get here, no exceptions have been thrown, so it's
		// safe to assume the result is an array.

		if (array_key_exists($field, $res))
			return $res[$field];

		return null; // Should we throw an exception?
	}

	// GetRecords()
	//	Execute the query, and return $limit rows, or all rows
	//
	public function GetRecords($query, $params=array(), $limit=0)
	{
		$res =& $this->Read($query, $params, $limit);
		$rows = $res->fetchAll();
		$res->free();

		return $rows;
	}

	// UpdateRecord()
	//	Execute the query provided and return the number of rows affected
	//
	public function UpdateRecord($query, $params=array())
	{
		return $this->Write($query, $params);
	}

	// InsertRecord()
	//	Execute the query provided and return the new record ID if available
	//
	public function InsertRecord($query, $params=array(), $noReturnId=FALSE)
	{
		$rec = $this->Write($query, $params);
		if ($noReturnId)
			return null;

		// Get the ID if we can
		$rec_id = $this->db->lastInsertID();
		if (MDB2::isError($rec_id))
			throw new Exception('CSDatabase::InsertRecord(): could not get lastInsertID: '.$rec_id->getMessage());

		return $rec_id;
	}
}

?>
Return current item: Network Configuration Store