PHP Classes: Database Connection

This is the MySQL database connection class I currently use. The connecting magic is done in the class constructor, so I only need to instantiate the class to connect. The static member is useful for ensuring only one connection is used up no matter how many times the class is instantiated.

Requires PHP version 5 or later.

+ –

Database Connection Class:

<?php
class DatabaseConnection
{
/*Database connection credentials*/
private $Host = "localhost"; // or 127.0.0.1
private $UserName = "uname";
private $Password = "pass";
private $Database = "databasename";

/* used to prevent unnecessary connections after the first one */
private static $db = NULL;

public function __construct( )
{
if(is_null(self::$db))
{
//make a conection to the database
mysql_connect($this->Host, $this->Username, $this->Password, self::$db) or
die("Could Not Connect to Database");

// select the database to use mysql_select_db($this->Database) or
die("Failed Selecting DB");

//denull the connection checker
self::$db = "not null";
}
}

public function __destruct( )
{
//if the connection closes, NULL the $db var
if(isset(self::$db))
{
self::$db = NULL;
mysql_close();
}
}

//used for inserts/updates/deletes, will return true if it succeeds and false if it fails
public function ExecuteNonQuery($Query_String)
{
$Query_ID = mysql_query($Query_String);

if(!$Query_ID)
return false;
else
return true;
}

//returns the result set of the query in a 2D array, returns false if the query fails
public function ExecuteSelectQuerySet($Query_String)
{
$Resource = mysql_query($Query_String);

if(!$Resource)
return false;
else
{
$DataSet = array();
//turn mysql resource into 2D array and return
while($Record = mysql_fetch_array($Resource))
{
array_push($DataSet, $Record);
}
return $DataSet;
}
}

//returns a single data row as an array from a query passed in, returns false if the query fails
public function ExecuteSelectQueryRow($Query_String)
{
$Resource = mysql_query($Query_String);

if(!$Resource)
return false;
else
{
//turn mysql resource into an array
$DataRow = mysql_fetch_array($Resource);

return $DataRow;
}
}
}
?>
Comments (0)
+ –