jilo-web/app/helpers/database.php

72 lines
2.5 KiB
PHP
Raw Normal View History

2024-08-10 18:42:44 +00:00
<?php
// connect to database
function connectDB($config, $database = '', $platform_id = '') {
2024-08-10 18:57:41 +00:00
// connecting ti a jilo sqlite database
2024-08-10 18:57:41 +00:00
if ($database === 'jilo') {
2024-08-10 18:42:44 +00:00
try {
$dbFile = $config['platforms'][$platform_id]['jilo_database'] ?? null;
if (!$dbFile) {
throw new Exception("Invalid platform ID \"$platform_id\", database file not found.");
}
2024-08-10 18:42:44 +00:00
$db = new Database([
2024-08-10 18:57:41 +00:00
'type' => 'sqlite',
'dbFile' => $dbFile,
2024-08-10 18:42:44 +00:00
]);
} catch (Exception $e) {
if ($config['environment'] === 'production') {
$error = 'There was an unexpected error. Please try again.';
} else {
$error = 'Error: ' . $e->getMessage();
}
2024-08-12 11:12:24 +00:00
include '../app/templates/block-message.php';
2024-08-10 18:42:44 +00:00
exit();
}
2024-08-10 18:57:41 +00:00
// connecting to a jilo-web database of the web app
2024-08-10 18:57:41 +00:00
} else {
// sqlite database file
2024-08-13 14:53:52 +00:00
if ($config['db']['db_type'] === 'sqlite') {
2024-08-10 18:57:41 +00:00
try {
$db = new Database([
2024-08-13 14:53:52 +00:00
'type' => $config['db']['db_type'],
'dbFile' => $config['db']['sqlite_file'],
2024-08-10 18:57:41 +00:00
]);
$pdo = $db->getConnection();
} catch (Exception $e) {
$error = 'Error: ' . $e->getMessage();
2024-08-12 11:12:24 +00:00
include '../app/templates/block-message.php';
2024-08-10 18:57:41 +00:00
exit();
}
// mysql/mariadb database
2024-08-13 14:53:52 +00:00
} elseif ($config['db']['db_type'] === 'mysql' || $config['db']['db_type'] === 'mariadb') {
2024-08-10 18:57:41 +00:00
try {
$db = new Database([
2024-08-13 14:53:52 +00:00
'type' => $config['db']['db_type'],
'host' => $config['db']['sql_host'] ?? 'localhost',
'port' => $config['db']['sql_port'] ?? '3306',
'dbname' => $config['db']['sql_database'],
'user' => $config['db']['sql_username'],
'password' => $config['db']['sql_password'],
2024-08-10 18:57:41 +00:00
]);
$pdo = $db->getConnection();
} catch (Exception $e) {
$error = 'Error: ' . $e->getMessage();
2024-08-12 11:12:24 +00:00
include '../app/templates/block-message.php';
2024-08-10 18:57:41 +00:00
exit();
}
// unknown database
} else {
2024-08-13 14:53:52 +00:00
$error = "Error: unknow database type \"{$config['db']['db_type']}\"";
2024-08-12 11:12:24 +00:00
include '../app/templates/block-message.php';
2024-08-10 18:42:44 +00:00
exit();
}
2024-08-10 18:57:41 +00:00
2024-08-10 18:42:44 +00:00
}
2024-08-10 18:57:41 +00:00
2024-08-10 18:42:44 +00:00
return $db;
}
?>