From 9aca57c01f17b253d4f388e90b1dc8599b0caebe Mon Sep 17 00:00:00 2001 From: Jordy van Zeeland Date: Wed, 14 Aug 2024 16:41:14 +0200 Subject: [PATCH] Database class --- database.php | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 database.php diff --git a/database.php b/database.php new file mode 100644 index 0000000..4fc7972 --- /dev/null +++ b/database.php @@ -0,0 +1,92 @@ +pdo = new PDO('mysql:host=' . $db_config['host'] . ';dbname=' . $db_config['database'] . ';charset=utf8mb4', $db_config['username'], $db_config['password']); + } + + public function select($columns = "*"){ + $this->type = "SELECT"; + $this->columns = $columns; + } + + public function from($table){ + $this->table = $table; + } + + public function where($key, value){ + $this->where = array($key, $value); + } + + public function andWhere($key, value){ + if(!$this->where) $this->where = array(); + $this->where[$key] = $value; + } + + public function limit($number){ + $this->limit = $number; + } + + public function all(){ + $this->query = $this->type . ' ' . $this->columns . ' FROM ' . $this->table; + + if(!empty($this->where)){ + $whereClauses = []; + foreach($this->where as $condition){ + $whereClauses[] = $condition[0] . ' = :"' . $condition[0]; + } + $this->query .= ' WHERE ' . implode(' AND ', $whereClauses); + } + + if(!empty($this->limit)){ + $this->query .= ' LIMIT ' . $this->limit; + } + + $results = $this->pdo->prepare($Query); + foreach($this->where as $condition){ + $results->bindValue(':' . $condition[0], $condition[1]); + } + + $results->execute(); + return $results->fetchAll(); + } + + public function one(){ + $this->query = $this->type . ' ' . $this->columns . ' FROM ' . $this->table; + + if(!empty($this->where)){ + $whereClauses = []; + foreach($this->where as $condition){ + $whereClauses[] = $condition[0] . ' = :"' . $condition[0]; + } + $this->query .= ' WHERE ' . implode(' AND ', $whereClauses); + } + + $this->query .= " LIMIT " . $this->limit; + + $results = $this->pdo->prepare($Query); + foreach($this->where as $condition){ + $results->bindValue(':' . $condition[0], $condition[1]); + } + + $results->execute(); + return $results->fetch(); + } +} + +// Database::select(id, name)->from('tablename')->all() +// Database::select(id, name)->from('tablename')->limit(100)->all() +// Database::select()->from('tablename')->where('id', 3)->one() + +?> \ No newline at end of file