-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig.php
More file actions
67 lines (49 loc) · 1.71 KB
/
config.php
File metadata and controls
67 lines (49 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
require_once __DIR__ . '/vendor/autoload.php';
// Set the timezone to Kolkata
date_default_timezone_set('Asia/Kolkata');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
// Database credentials
$servername = $_ENV['DB_SERVER'];
$username = $_ENV['DB_USERNAME'];
$password = $_ENV['DB_PASSWORD'];
$db_name = $_ENV['DB_NAME'];
$baseurl = $_ENV['BASE_URL'];
try {
$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) {
throw new Exception("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");
$conn->query("SET SESSION sql_mode = 'STRICT_ALL_TABLES'");
// Output a success message (optional)
// echo "Database connection successful!";
} catch (Exception $e) {
// Log the error message for debugging
error_log("Database connection error: " . $e->getMessage());
// Display a user-friendly error message
http_response_code(500);
die("An error occurred while connecting to the database. Please try again later.");
}
// Close the database connection when it's no longer needed
function closeDatabaseConnection($conn) {
$conn->close();
}
// Register the function to close the database connection when the script ends
register_shutdown_function(function() use ($conn) {
closeDatabaseConnection($conn);
});
// Example usage of the database connection
function getUserData($conn, $userId) {
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
return $result->fetch_assoc();
}
$userId = 1;
$userData = getUserData($conn, $userId);
print_r($userData);
closeDatabaseConnection($conn);
?>