Files
xxx/open_db.lib.php
T

55 lines
1.7 KiB
PHP

<?php
require_once(__DIR__ . '/config.lib.php');
global $db;
/*
* The class of the connection that open_db() makes. It is always mysqli
* on the site; the tests put a fake class in the global $db_class.
*/
function open_db($state) {
global $db, $db_class;
if ($state == 'open') {
if (!$db) {
$hostname = config('DB_HOST', 'localhost');
$view_user = config('DB_USER');
$view_pass = config('DB_PASS');
$db_name = config('DB_NAME');
// PHP 8.1+ throws exceptions by default; keep the old return-value checks working
mysqli_report(MYSQLI_REPORT_OFF);
$class = $db_class ?? 'mysqli';
$db = new $class($hostname, $view_user, $view_pass, $db_name);
if ($db->connect_error) {
$detail = 'connect error (' . $db->connect_errno . ') ' . $db->connect_error;
$db = NULL;
db_fail($detail);
}
return TRUE;
} else
return FALSE;
}
else if ($state == 'close') {
if ($db) {
$db->close();
$db = NULL;
return TRUE;
} else
return FALSE;
}
}
/*
* Stop the page after a database error. The details, with the file and
* line of the failed call, go to the PHP error log; the visitor only
* sees a short apology.
*/
function db_fail($detail = NULL) {
global $db;
if ($detail === NULL)
$detail = $db ? $db->error : 'no database connection';
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
error_log('xxx: database error at ' . basename($caller['file']) . ':' . $caller['line'] . ': ' . $detail);
if (!headers_sent())
header('HTTP/1.1 500 Internal Server Error');
die('<p>Sorry, something went wrong. Please try again later.</p>');
}
?>