require_once("properties.php");
class DbConnection
{
private $connectionId;
private function __construct($dbHost,$dbUser,$dbPassword,$dbName)
{
$this->connectionId =
mysql_connect($dbHost,$dbUser,$dbPassword,true);
if($this->connectionId)
{
$this->selectDatabase($dbName);
}
else
{
throw new Exception(mysql_error());
}
}
private function selectDatabase($db)
{
$dbSelected = mysql_select_db($db,$this->connectionId);
if(!$dbSelected)
{
throw new Exception(mysql_error());
}
}
function __destruct()
{
if(is_resource($this->connectionId))
{
$this->closeConnection();
}
}
public function closeConnection()
{
mysql_close($this->connectionId);
}
public function getResourceId()
{
return $this->connectionId;
}
public static function getInstance()
{
static $dbConnObj;
if(!isset($dbConnObj))
{
$dbConnObj = new DbConnection(HOSTNAME,DB_USER,DB_PWD,DB_NAME);
}
return $dbConnObj;
}
public function prepareQuery($args=null)
{
$resourceId = $this->getResourceId();
$args = func_get_args();
$query = array_shift($args);
foreach($args as $argIndex=>$param)
{
$args[$argIndex] = mysql_real_escape_string($param,$resourceId);
}
return vsprintf($query,$args);
}
public function fetchRow($query)
{
$recordDetails = $this->executeQuery($query);
return $recordDetails[0]? get_object_vars($recordDetails[0]) : null;
}
public function fetchVar($query)
{
$recordDetails = $this->fetchRow($query);
if(count($recordDetails)>0)
{
$values = array_values($recordDetails);
}
if(isset($values[0]) && $values[0]!=='')
{
return $values[0];
}
}
public function executeQuery($query)
{
$resourceId = $this->getResourceId();
$result = @mysql_query($query,$resourceId);
if( preg_match("/^\\s*(insert|update|delete|replace|alter)/i",$query) ){
$returnVal = mysql_affected_rows($resourceId);
}
else{
$resultSet = array();
while($row = @mysql_fetch_object($result))
{
$resultSet[] = $row;
}
$returnVal = $resultSet;
}
return $returnVal;
}
}
try{
$dbConn = DbConnection::getInstance();
}catch(Exception $e){
die("
Error:".$e->getMessage());
}
Note:
1. HOSTNAME
2. DB_USER
3. DB_PWD
4. DB_NAME are constants defined in
properties.php
No comments:
Post a Comment