<?php
// database.php
require_once __DIR__ . '/config.php'; // Ensure this path correctly points to config.php
/**
* Establish a new database connection.
*
* @return mysqli The MySQLi database connection object.
* @throws Exception if the connection fails.
*/
function db_connect()
{
// Use MySQLi to connect to the database
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check if the connection was successful
if ($connection->connect_error) {
error_log("Database connection failed: " . $connection->connect_error);
die("Database connection failed. Please check the error log for details.");
}
// Set the character set to UTF-8 for proper handling of characters
if (!$connection->set_charset("utf8mb4")) {
error_log("Error setting character set utf8mb4: " . $connection->error);
}
return $connection;
}
/**
* Close an existing database connection.
*
* @param mysqli|null $connection The connection object to close.
* @return void
*/
function db_disconnect($connection)
{
if ($connection instanceof mysqli) {
$connection->close();
}
}
// Establish a connection and store it in the variable $db for use later
$db = db_connect();
// You can now use $db for your database queries