Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.00 KB | None | 0 0
  1. <?php
  2.  
  3. class DBTable {
  4.     private $Conn;
  5.     private $table;
  6.     private $primaryKey;
  7.  
  8.     public function __construct(PDO $Conn, string $table, string $primaryKey) {
  9.         $this->Conn = $Conn;
  10.         $this->table = $table;
  11.         $this->primaryKey = $primaryKey;
  12.     }
  13.  
  14.     private function prep_exec($sql, $params=[]) {
  15.         $stmt = $Conn -> prepare($sql);
  16.         $stmt->execute($params);
  17.         return $stmt;
  18.     }
  19.  
  20.     private function fetchAsArray($query) {
  21.         while ($row = $query->fetch()) {
  22.             $rows[] = $row;
  23.         }
  24.         return $rows;
  25.     }
  26.  
  27.     public function selectAll() {
  28.         $query = 'SELECT * FROM `' . $table . '`';
  29.        
  30.         $query = $this->prep_exec($query);
  31.         $array = fetchAsArray($query);
  32.  
  33.         return $array;
  34.     }
  35.  
  36.     public function selectByPKey($value) {
  37.         $query = 'SELECT * FROM `' . $table . '` WHERE `' . $primaryKey . '` = :value';
  38.  
  39.         $params = [
  40.             'value' => $value
  41.         ];
  42.  
  43.         $query = $this->prep_exec($query, $params);
  44.         $array = fetchAsArray($query);
  45.  
  46.         return $array;
  47.     }
  48.  
  49.     private function insert($params) {
  50.         $query = 'INSERT INTO `' . $table . '` (';
  51.  
  52.         foreach ($params as $key => $val) {
  53.             $query .= '`' . $key . '`,';
  54.         }
  55.  
  56.         $query = rtrim($query, ',');
  57.  
  58.         $query .= ') VALUES (';
  59.  
  60.         foreach($params as $key => $val) {
  61.             $query .= ':' . $key . ', ';
  62.         }
  63.  
  64.         $query .= ')';
  65.  
  66.         $this->prep_exec($query, $params);
  67.     }
  68.  
  69.     private function update($params) {
  70.         $query = 'UPDATE `' . $table .'` SET ';
  71.  
  72.         foreach($params as $key => $val) {
  73.             $query .= '`' . $key . '` = :' . $key . ', ';
  74.         }
  75.  
  76.         $query = rtrim($query, ',');
  77.  
  78.         $query .= 'WHERE `' . $primaryKey . '` = :primaryKey';
  79.  
  80.         //Set primaryKey Var
  81.         $params['primaryKey'] = $params['id'];
  82.  
  83.         $this->prep_exec($query, $params);
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement