Wednesday, August 22, 2007

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;
}

}
?>

No comments: