Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DBTable {
- private $Conn;
- private $table;
- private $primaryKey;
- public function __construct(PDO $Conn, string $table, string $primaryKey) {
- $this->Conn = $Conn;
- $this->table = $table;
- $this->primaryKey = $primaryKey;
- }
- private function prep_exec($sql, $params=[]) {
- $stmt = $Conn -> prepare($sql);
- $stmt->execute($params);
- return $stmt;
- }
- private function fetchAsArray($query) {
- while ($row = $query->fetch()) {
- $rows[] = $row;
- }
- return $rows;
- }
- public function selectAll() {
- $query = 'SELECT * FROM `' . $table . '`';
- $query = $this->prep_exec($query);
- $array = fetchAsArray($query);
- return $array;
- }
- public function selectByPKey($value) {
- $query = 'SELECT * FROM `' . $table . '` WHERE `' . $primaryKey . '` = :value';
- $params = [
- 'value' => $value
- ];
- $query = $this->prep_exec($query, $params);
- $array = fetchAsArray($query);
- return $array;
- }
- private function insert($params) {
- $query = 'INSERT INTO `' . $table . '` (';
- foreach ($params as $key => $val) {
- $query .= '`' . $key . '`,';
- }
- $query = rtrim($query, ',');
- $query .= ') VALUES (';
- foreach($params as $key => $val) {
- $query .= ':' . $key . ', ';
- }
- $query .= ')';
- $this->prep_exec($query, $params);
- }
- private function update($params) {
- $query = 'UPDATE `' . $table .'` SET ';
- foreach($params as $key => $val) {
- $query .= '`' . $key . '` = :' . $key . ', ';
- }
- $query = rtrim($query, ',');
- $query .= 'WHERE `' . $primaryKey . '` = :primaryKey';
- //Set primaryKey Var
- $params['primaryKey'] = $params['id'];
- $this->prep_exec($query, $params);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement