<?php

require_once(dirname(__FILE__).'/statement.php');

class Connection
{
	var $_dbLink;

	function Connection($server = '', $databaseName = '', $userName = '', $password = '', $encoding = 'utf8')
	{
		$this->_dbLink = mysql_connect($server, $userName, $password);
		if ($this->_dbLink === false)
		{
			ErrorHandler::TriggerError('Can\'t connect to database server.', E_ERROR);
		}
		else
		{
			if (mysql_select_db($databaseName, $this->_dbLink) === false)
			{
				ErrorHandler::TriggerError("Can't select database", E_ERROR);
			}
		}
		mysql_query("SET NAMES ".$this->GetSQLString($encoding));
	}

	function &CreateStatement($resultType = MYSQL_ASSOC, $errorLevel = E_USER_WARNING)
	{
		$stmt =& new Statement($this->_dbLink, $resultType, $errorLevel);
		return $stmt;
	}

	function GetSQLString($str)
	{
		if (is_null($str))
		{
			return "NULL";
		}
		return "'".mysql_escape_string($str)."'";
	}

	function GetSQLLike($str)
	{
		return addcslashes(mysql_escape_string($str), "\\_%'");
	}

	function GetSQLArray($arr)
	{
		if (is_array($arr))
		{
			foreach ($arr as $key => $value)
				$arr[$key] = Connection::GetSQLString($value);
		}
		return $arr;
	}
}

?>