Wednesday, August 22, 2007

php 5 mysqli wrapper - error handler


// mysql error class
class MySqlError{

//
// private members
//

private $Server;
private $User;
private $Date;
private $Script;
private $Referrer;
private $Environment;

//
// public members
//

public $Database;
public $Message;
public $CommandText;
public $Parameters;

//
// constructor
//

public function __construct() {

$this->Server = $_SERVER['SERVER_NAME'];
$this->User = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '';
$this->Date = date('Y-m-d H:i:s');
$this->Script = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
$this->Referrer = $_SERVER['HTTP_REFERER'];
$this->Environment = $this->var_dump_ret($_REQUEST);
}

//
// private methods
//

// return var_dump as a string
private function var_dump_ret($mixed) {

ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}

//
// public methods
//

// log error message to file and send email
public function Log() {

$message = 'User: ' . $this->User . "\n"
. 'Date: ' . $this->Date . "\n"
. 'Script: ' . $this->Script . "\n"
. 'Referrer: ' . $this->Referrer . "\n\n"
. 'Message: ' . $this->Message . "\n\n"
. 'CommandText: ' . "\n" . $this->CommandText . "\n\n"
. 'Parameters: ' . "\n" . $this->var_dump_ret($this->Parameters) . "\n"
. 'Environment: ' . "\n" . $this->Environment;

// append message to log file if it exists
if($handle = fopen(SITE_DIR . 'logs/errors.txt','ab')){

fwrite($handle, $message);
fclose($handle);
}

// email message
$oMail = new cMail();
$oMail->from = 'you@domain.com';
$oMail->addTo('you@domain.com');
$oMail->subject = "Website Error";
$oMail->message = $message;
$oMail->send();
}

}
?>

php 5 mysqli wrapper - data reader


// mysql data reader class
class MySqlDataReader{

//
// private members
//

private $Statement;
private $Results;
private $Bound;

//
// constructor
//

public function __construct($Statement = ''){

$this->Statement = $Statement;
$this->Bound = false;
}

//
// private methods
//

// bind output parameters
private function BindResults(){

if(count($this->Results)){

$this->Bound = true;
// $this->Statement->bind_result($this->Results[0], $this->Results[1], ...);
call_user_func_array(array($this->Statement, 'bind_result'), $this->Results);
}
}

//
// public methods
//

// helper method for adding bound results
public function AddResult(&$result){
$this->Results[] = &$result;
}

// read data from database
public function Read(){

// bind result parameters on first call to read
if(!$this->Bound)
$this->BindResults();

// fetch next row of data
if(is_object($this->Statement))
return $this->Statement->fetch();
}

// close the statement if it hasn't been closed already
public function Close(){

if(is_object($this->Statement))
$this->Statement->close();
}

}
?>

php 5 mysqli wrapper - command


// wrapper for mysqli statement object
class MySqlCommand{

//
// private members
//

private $Statement; // prepared statement

//
// public members
//

public $CommandText; // sql to execute
public $Connection; // mysqli object
public $Parameters = array(); // array of input parameters
public $Results = array(); // array of output parameters

//
// constructor
//

public function __construct($CommandText = '', $Connection = ''){

$this->CommandText = $CommandText;
$this->Connection = $Connection;
}

//
// private methods
//

// bind input parameters
private function BindParameters(){

if(count($this->Parameters)){

// determine type of input parameter (i)nteger/(d)ouble/(s)tring
$types = '';
foreach ($this->Parameters as $Parameter){

if(is_int($Parameter))
$types .= 'i';
elseif(is_float($Parameter))
$types .= 'd';
else
$types .= 's';
}

// $this->Statement->bind_param($types, $this->Parameters[0], $this->Parameters[1], ...);
call_user_func_array(array($this->Statement, 'bind_param'), array_merge(array($types), $this->Parameters));
}
}

// log errors
private function handle_exception(){

$oMySqlError = new MySqlError();
$oMySqlError->Message = $this->Connection->Error();
$oMySqlError->CommandText = $this->CommandText;
$oMySqlError->Parameters = $this->Parameters;
$oMySqlError->Log();
$oMySqlError = null;
}

//
// public methods
//

// helper method for adding bound parameters
public function AddParameter(&$parameter){
$this->Parameters[] = &$parameter;
}

// close the statement if it hasn't been closed already
public function Close(){

if(is_object($this->Statement))
$this->Statement->close();
}

// execute a non-query, like insert, update, delete
public function ExecuteNonQuery(){

try{

// prepare statement
if(!$this->Statement = $this->Connection->Prepare($this->CommandText))
throw new Exception();

// bind input parameters
$this->BindParameters();

// execute statement
if(!$this->Statement->execute())
throw new Exception();
}
catch (Exception $e){

$this->handle_exception();
}
}

// return a data reader from a select statement
public function ExecuteReader(){

try{

// prepare statement
if(!$this->Statement = $this->Connection->Prepare($this->CommandText))
throw new Exception();

// bind input parameters
$this->BindParameters();

// execute statement
if(!$this->Statement->execute())
throw new Exception();
}
catch (Exception $e){

$this->handle_exception();
}

// create and return a new data reader for statement
$oDataReader = new MySqlDataReader($this->Statement);
return $oDataReader;
}

// return a scalar value
public function ExecuteScalar(){

try{

// prepare statement
if(!$this->Statement = $this->Connection->Prepare($this->CommandText))
throw new Exception();

// bind input parameters
$this->BindParameters();

// execute statement
if(!$this->Statement->execute())
throw new Exception();
}
catch (Exception $e){

$this->handle_exception();
}

// create a data reader
$oDataReader = new MySqlDataReader($this->Statement);
// bind the result
$oDataReader->AddResult($result);
// execute the reader
if(!$oDataReader->Read())
$result = null;
$oDataReader = null;

// return the result
return $result;
}

}
?>

php 5 mysqli wrapper - connection


// wrapper for mysqli object
class MySqlConnection{

//
// private members
//

private $Connection; // mysqli object

private $username;
private $password;
private $database;
private $server;

//
// constructor
//

// $ConnectionString
// semi-colon delimited connection string ex. server=localhost;username=root;password=root;database=test;
public function __construct($ConnectionString){

// parse connection string
$param_array = split(';', $ConnectionString);
foreach ($param_array as $param_pair){

$param_pair = trim($param_pair);
if(strlen($param_pair)){

$param = split('=', $param_pair);
$param[0] = strtolower(trim($param[0]));
$param[1] = trim($param[1]);

$this->$param[0] = $param[1];
}
}
}

// close database connection
public function Close(){

$this->Connection->close();
}

// open database connection
public function Open(){

$this->Connection = new mysqli($this->server, $this->username, $this->password, $this->database);
if (mysqli_connect_errno()){

$oMySqlError = new MySqlError();
$oMySqlError->Database = $this->database;
$oMySqlError->Message = $this->Connection->error;

$oMySqlError->Log();
}
}

// prepare and return sql statement
public function Prepare($CommandText){

return $this->Connection->prepare($CommandText);
}

// return last error message
public function Error(){

return $this->Connection->error;
}

// return last auto-generated id
public function InsertId(){

return $this->Connection->insert_id;
}

}
?>