Update databaseConnection/databaseConnection.php
This commit is contained in:
parent
08a888e270
commit
8d84b0959d
|
|
@ -1,10 +1,62 @@
|
||||||
<?php
|
<?php
|
||||||
|
|
||||||
function getDatabaseConnection() {
|
// Lädt die .env Datei zwei Ordner über dieser Datei
|
||||||
$databaseAddress = "127.0.0.1";
|
function loadEnv(): void
|
||||||
$databasePort = "3306";
|
{
|
||||||
$databaseName = "";
|
$envPath = dirname(__DIR__, 2) . '/.env';
|
||||||
$databaseUser = "";
|
|
||||||
$databasePassword = "";
|
if (!file_exists($envPath)) {
|
||||||
return new mysqli($databaseAddress, $databaseUser, $databasePassword, $databaseName);
|
throw new RuntimeException('.env file not found at: ' . $envPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||||
|
|
||||||
|
foreach ($lines as $line) {
|
||||||
|
$line = trim($line);
|
||||||
|
|
||||||
|
if ($line === '' || str_starts_with($line, '#')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
[$key, $value] = array_pad(explode('=', $line, 2), 2, '');
|
||||||
|
|
||||||
|
$key = trim($key);
|
||||||
|
$value = trim($value);
|
||||||
|
|
||||||
|
$_ENV[$key] = $value;
|
||||||
|
putenv("$key=$value");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// .env einmal laden
|
||||||
|
loadEnv();
|
||||||
|
|
||||||
|
function env(string $key, $default = null)
|
||||||
|
{
|
||||||
|
return $_ENV[$key] ?? getenv($key) ?? $default;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDatabaseConnection(): mysqli
|
||||||
|
{
|
||||||
|
$databaseAddress = env('DB_HOST', '127.0.0.1');
|
||||||
|
$databasePort = env('DB_PORT', '3306');
|
||||||
|
$databaseName = env('DB_NAME');
|
||||||
|
$databaseUser = env('DB_USER');
|
||||||
|
$databasePassword = env('DB_PASS');
|
||||||
|
|
||||||
|
$mysqli = new mysqli(
|
||||||
|
$databaseAddress,
|
||||||
|
$databaseUser,
|
||||||
|
$databasePassword,
|
||||||
|
$databaseName,
|
||||||
|
(int) $databasePort
|
||||||
|
);
|
||||||
|
|
||||||
|
if ($mysqli->connect_error) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
'Database connection failed: ' . $mysqli->connect_error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $mysqli;
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue