-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhandler.php
76 lines (63 loc) · 2 KB
/
handler.php
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
68
69
70
71
72
73
74
75
76
<?php
function insertRecord($mysqli, $tableName, $data) {
// Check if mysqli object is null
if ($mysqli === null) {
die("Database connection is not established.");
}
// Create table if it doesn't exist
$createTableSql = "CREATE TABLE IF NOT EXISTS `$tableName` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if ($mysqli->query($createTableSql) === FALSE) {
die("Error creating table: " . $mysqli->error);
}
// Prepare SQL statement
$stmt = $mysqli->prepare("INSERT INTO $tableName (email, reg_date) VALUES (?, NOW())");
if ($stmt === false) {
die("Error preparing statement: " . $mysqli->error);
}
// Bind parameters
$stmt->bind_param("s", $data['email']);
// Execute statement
if ($stmt->execute() === false) {
die("Error executing statement: " . $stmt->error);
}
echo "Record inserted successfully";
$stmt->close();
}
function handle($event, $context) {
$dbHost = getenv('MYSQL_HOST');
$dbUsername = getenv('MYSQL_USER');
$dbPassword = getenv('MYSQL_PASSWORD');
$dbName = getenv('MYSQL_DB');
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
$tableName = "users";
if ($mysqli === null) {
die("Database connection is not established.");
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Extract user data from the request
$data = json_decode($event['body'], true);
if ($data === null || $data['email'] === null) {
return [
"body" => "Email is required",
"statusCode" => 400,
];
}
try {
insertRecord($mysqli, $tableName, $data);
} catch (Exception $e) {
return [
"body" => "Error: " . $e->getMessage(),
"statusCode" => 500,
];
}
return [
"body" => "Inserted " . $data['email'] . " into the database",
"statusCode" => 200,
];
}