-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdb.php
79 lines (65 loc) · 2.06 KB
/
db.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
77
78
79
<?php
class Database {
private static $instance;
private $connection;
private function __construct() {
$servername = "mysql-p";
$username = "p3379031rw";
$password = substr(file_get_contents(".env"), strlen("password="));
if (substr($password, -1, 1) == "\n") {
$password = substr($password, 0, strlen($password) - 1);
}
if (substr($password, -1, 1) == "\r") {
$password = substr($password, 0, strlen($password) - 1);
}
$dbname = "p3379031_assembler_db";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
$conn = Database::getInstance()->getConnection();
if (isset($_POST['code'])) {
$code = $_POST['code'];
$stmt = $conn->prepare("INSERT INTO programs (code) VALUES (:code)");
$stmt->bindParam(':code', $code);
try {
$stmt->execute();
$lastInsertedId = $conn->lastInsertId();
echo "?id=" . $lastInsertedId;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
if ($id == "") {
echo "NO";
return;
}
$stmt = $conn->prepare("SELECT code FROM programs WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
$programCode = $result['code'];
// mysql uses \r\n, the browser uses \n
$programCode = str_replace("\r\n", "\n", $programCode);
echo $programCode;
} else {
echo "Program not found!";
}
}
?>