Encapsulation and Modularity:
- The class encapsulates the database connection details and operations, promoting a modular and organized code structure.
- Private properties, such as
$Host
, $User
, $Pass
, and $DB_Name
, encapsulate sensitive information, preventing direct access from outside the class.
Constructor Initialization:
The constructor method (__construct()
) initializes the database connection using PDO, setting up the Data Source Name (DSN) and providing options for error handling and result fetching modes.
It throws an exception in case of a connection failure, providing a clear error message.
Prepared Statements:
The Query()
, Bind()
, and Execute()
methods facilitate the use of prepared statements, protecting against SQL injection.
The class automatically detects the parameter type in the Bind()
method, enhancing usability.
Result Retrieval Methods:
The class provides methods like ResultSet()
and Single()
for fetching result sets and single rows respectively, making it convenient to handle different types of queries.
The RowCount()
method returns the number of rows affected by the last query, aiding in error checking.
Transaction Support:
Methods like StartTransaction()
, EndTransaction()
, and CancelTransaction()
allow users to easily handle database transactions, ensuring data integrity.
Convenient Methods:
The class includes helpful methods such as LastID()
to retrieve the last inserted ID and Quote()
for proper escaping and quoting of values.
DebugParams()
provides a formatted output of the statement and bindings for debugging purposes.
<?php
class DataBase {
private $Host = DB_HOST;
private $User = DB_USER;
private $Pass = DB_PASS;
private $DB_Name = DB_NAME;
private $DBH;
private $STMT;
public function __construct() {
$DSN = 'mysql:host=' . $this->Host . ';dbname=' . $this->DB_Name;
$Options = array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
try {
$this->DBH = new PDO($DSN, $this->User, $this->Pass, $Options);
} catch(PDOException $e) {
throw new Exception("Database connection failed: " . $e->getMessage());
}
}
public function Query($Query) {
try {
$this->STMT = $this->DBH->prepare($Query);
} catch(PDOException $e) {
throw new Exception("Query preparation error: " . $e->getMessage());
}
}
public function Bind($Param, $Value, $Type = null) {
try {
if (is_null($Type)) {
$Type = $this->DetectType($Value);
}
$this->STMT->bindValue($Param, $Value, $Type);
} catch(PDOException $e) {
throw new Exception("Binding error: " . $e->getMessage());
}
}
public function Execute() {
try {
return $this->STMT->execute();
} catch(PDOException $e) {
throw new Exception("Execution error: " . $e->getMessage());
}
}
public function ResultSet() {
if (!$this->STMT->rowCount()) {
$this->Execute();
}
return $this->STMT->fetchAll(PDO::FETCH_ASSOC);
}
public function Single() {
if (!$this->STMT->rowCount()) {
$this->Execute();
}
return $this->STMT->fetch(PDO::FETCH_ASSOC);
}
public function RowCount() {
return $this->STMT->rowCount();
}
public function LastID() {
return $this->DBH->lastInsertId();
}
public function StartTransaction() {
return $this->DBH->beginTransaction();
}
public function EndTransaction() {
return $this->DBH->commit();
}
public function CancelTransaction() {
return $this->DBH->rollBack();
}
public function Quote($value) {
return $this->DBH->quote($value);
}
public function DebugParams() {
$output = "Statement:\n" . $this->STMT->queryString . "\n";
$output .= "Bindings:\n";
$bindings = $this->STMT->debugDumpParams();
$output .= str_replace("\n", "\n ", $bindings);
return $output;
}
private function DetectType($value) {
if (is_int($value)) {
return PDO::PARAM_INT;
} elseif (is_bool($value)) {
return PDO::PARAM_BOOL;
} elseif (is_null($value)) {
return PDO::PARAM_NULL;
} else {
return PDO::PARAM_STR;
}
}
}
?>