DatabaseHandler
The DatabaseHandler
class in Quanta provides a simple abstraction layer for interacting with a MySQL database using PDO. It handles database connections, query execution, and fetching results. The class also provides methods to fetch the last inserted ID and directly access the PDO instance for advanced operations.
The DatabaseHandler
Class Structure
The DatabaseHandler
class is designed to manage the connection to a MySQL database and execute queries using PDO. The class provides methods for initializing the connection, querying the database, and retrieving the last inserted record's ID.
Example Usage:
Initializing the Database Connection:
$quanta->databaseHandler->init(DB_HOST, DB_NAME, DB_USER, DB_PW);
Performing a Query:
$sql = "SELECT * FROM users WHERE email = ?";
$params = ['user@example.com'];
$result = $quanta->databaseHandler->query($sql, $params);
foreach ($result as $row) {
echo $row['name'];
}
Inserting a Record and Getting the Last Insert ID:
$sql = "INSERT INTO users (email, name) VALUES (?, ?)";
$params = ['user@example.com', 'John Doe'];
$quanta->quanta->databaseHandler->query($sql, $params);
$lastInsertId = $quanta->databaseHandler->lastInsertId();
echo "Last Insert ID: " . $lastInsertId;
Accessing the PDO Instance:
$pdo = $quanta->databaseHandler->getPDO();
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();
Conclusion:
The DatabaseHandler
class provides a simple and effective way to interact with a MySQL database in a Quanta-based application. With support for prepared statements, querying, and retrieving the last inserted ID, this class helps you manage database operations in a secure and efficient manner.