Wednesday, April 22, 2009

Workaround for Maximum Script Execution time limit

We all know that the default execution time of a php script is set to 30 seconds, defined by the parameter max_execution_time in php.ini file.

A simple workaround to overcome the time limitation is a call to ini_set() as :

ini_set('max_execution_time','0')   //0 = no limit


This causes the current script to be executed without any maximum time limit. I found this workaround helpful in case of sending newsletters where bulk mailing is required. Hope it is helpful to you.

Creative Commons License

Tuesday, April 21, 2009

Singleton Design Pattern Example in PHP

Here is a sample example class that implements Singleton Design Pattern in PHP:

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



Creative Commons License