Database Class Documentation
Overview
The Database class provides a unified and modern approach to interact with MySQL databases using PDO. It supports prepared statements, transactions, and query logging through DebugBar.
Methods
init()
Initializes the PDO connection using configuration parameters from the .env file and sets up DebugBar if not in a testing environment.
Usage:
Database::init();
Demo Result:
Database connection established successfully.
prepare($sql)
Prepares an SQL statement.
Parameters:
$sql(string): The SQL query to prepare.
Usage:
$stmt = Database::prepare("SELECT * FROM users WHERE id = :id");
Demo Result:
PDOStatement object ready for execution.
lastInsertId()
Returns the ID of the last inserted row.
Usage:
$lastId = Database::lastInsertId();
Demo Result:
42
query($sql)
Executes an SQL query.
Parameters:
$sql(string): The SQL query to execute.
Usage:
$result = Database::query("SELECT * FROM users");
Demo Result:
PDOStatement object containing the result set.
beginTransaction()
Begins a transaction.
Usage:
Database::beginTransaction();
Demo Result:
Transaction started.
commit()
Commits the current transaction.
Usage:
Database::commit();
Demo Result:
Transaction committed.
rollback()
Rolls back the current transaction.
Usage:
Database::rollback();
Demo Result:
Transaction rolled back.
execute($sql, $params = [])
Executes a prepared statement with parameters.
Parameters:
$sql(string): The SQL query to execute.$params(array): An associative array of parameters to bind to the query.
Usage:
Database::execute("INSERT INTO users (username, password) VALUES (:username, :password)", ['username' => 'newuser', 'password' => 'securepassword']);
Demo Result:
Query executed successfully, 1 row affected.
fetchAll($sql, $params = [])
Executes a prepared statement and fetches all rows as an associative array.
Parameters:
$sql(string): The SQL query to execute.$params(array): An associative array of parameters to bind to the query.
Usage:
$users = Database::fetchAll("SELECT * FROM users WHERE status = :status", ['status' => 'active']);
Demo Result:
[
['id' => 1, 'username' => 'user1', 'status' => 'active'],
['id' => 2, 'username' => 'user2', 'status' => 'active'],
...
]
fetchOne($sql, $params = [])
Executes a prepared statement and fetches a single row as an associative array.
Parameters:
$sql(string): The SQL query to execute.$params(array): An associative array of parameters to bind to the query.
Usage:
$user = Database::fetchOne("SELECT * FROM users WHERE id = :id", ['id' => 1]);
Demo Result:
['id' => 1, 'username' => 'user1', 'status' => 'active']
affectedRows($stmt)
Returns the number of rows affected by the last operation on the statement.
Parameters:
$stmt(PDOStatement): The PDO statement object.
Usage:
$rows = Database::affectedRows($stmt);
Demo Result:
3
escape($value)
Escapes a value for use in an SQL query.
Parameters:
$value(string): The value to escape.
Usage:
$escapedValue = Database::escape("O'Reilly");
Demo Result:
'O'Reilly'