Summary Files Commits Branches @commit @diff @stats
path: root / src / models / DB.php
blob: 299b05a445c9b0c72a469a7a6a79e53ac81da2ea (plain) (blame)
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
<?php
class DB {
	private static $servername = "localhost";
	private static $username = "root";
	private static $password = "password";
	private static $dbname = "devrix_job_board";

	public const STRING_TYPE = "VARCHAR(100)";
	public const FLOAT_TYPE = "DOUBLE(16,4)";
	public const INTEGER_TYPE = "INT";

	private PDO $connection;

	function __construct() {
		$this->connection = new PDO("mysql:host=" . self::$servername, self::$username, self::$password);
		$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		// Make sure the actual db exists
		$createDBQuery = "CREATE DATABASE IF NOT EXISTS " . self::$dbname . ";";

		$this->connection->exec($createDBQuery);

		// Make the actual connection to the database
		$this->connection->exec("USE " . self::$dbname);
	}

	function createTable(string $tableName, array $columns) {
		$query = "CREATE TABLE IF NOT EXISTS {$tableName}(
				  id INT NOT NULL AUTO_INCREMENT,";

		foreach ($columns as $column) {
			$query .= "{$column},";
		}

		$query .= "PRIMARY KEY (id));";

		$this->connection->exec($query);
	}

	function getAllValues(string $tableName) {
		$sth = $this->connection->prepare("SELECT * FROM `{$tableName}`");
		$sth->execute();

		return $sth->fetchAll(PDO::FETCH_OBJ);
	}

	function insertValue(string $tableName, ...$values) {
		$query = "INSERT INTO {$tableName} VALUES(NULL, ";

		foreach($values as $value) {
			if (gettype($value) == "string") {
				$query .= "'{$value}', ";
			}
			else {
				$query .= "{$value}, ";
			}
		}
		$query = rtrim($query, ", ");

		$query .= ");";

		$this->connection->exec($query);
	}
}