aboutsummaryrefslogtreecommitdiff
path: root/models/database.php
diff options
context:
space:
mode:
Diffstat (limited to 'models/database.php')
-rw-r--r--models/database.php50
1 files changed, 50 insertions, 0 deletions
diff --git a/models/database.php b/models/database.php
new file mode 100644
index 0000000..ad0c574
--- /dev/null
+++ b/models/database.php
@@ -0,0 +1,50 @@
+<?php
+namespace Database;
+use PDO;
+
+class User {
+ public $UID;
+ public $Username;
+ public $Password;
+ public $Role;
+
+ function fromDB(string $username) : User {
+ $conn = connect();
+ $query = $conn->query("SELECT * FROM Users WHERE Username = \"$username\"");
+ // TODO: research if this is enough to close the connection, $query may store a reference
+ $conn = null;
+
+ if ($query->rowCount() == 0) {
+ throw new Exception("User $username doesn't exist!");
+ }
+ assert($query->rowCount() == 1, "Users must have unique usernames!");
+
+ $query->setFetchMode(PDO::FETCH_CLASS, "User");
+ return $query->fetch();
+ }
+
+ static function create(string $Username, string $Password, string $Role) {
+ $conn = connect();
+ $query = $conn->query("INSERT INTO Users (Username, Password, Role) VALUES (\"$Username\", \"$Password\", \"$Role\")");
+ $conn = null;
+ }
+
+ static function get_all() : array {
+ $conn = connect();
+ $query = $conn->query("SELECT * FROM Users");
+ $conn = null;
+
+ $query->setFetchMode(PDO::FETCH_CLASS, "Database\User");
+ return $query->fetchAll();
+ }
+}
+
+function connect() : PDO {
+ $conn = new PDO(
+ "mysql:unix_socket=" . getenv('MYSQL_UNIX_SOCKET') . ";dbname=nwfh",
+ getenv('USER'),
+ "");
+ // set the PDO error mode to exception
+ $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+ return $conn;
+}