Advertisement
Guest User

Untitled

a guest
Apr 14th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.91 KB | None | 0 0
  1. <?php
  2.  
  3. class Database
  4. {
  5.     private $host = "";
  6.     private $user = "";
  7.     private $pass = "";
  8.     private $name = "";
  9.  
  10.     private $pdo;
  11.  
  12.     public function __construct()
  13.     {
  14.         if (! isset($this->pdo))
  15.         {
  16.             try
  17.             {
  18.                 $link = new PDO("mysql:host = " . $this->host . "dbname = " . $this->name, $this->user, $this->pass);
  19.                 $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  20.                 $link->exec("SET CHARSET SET utf8");
  21.                
  22.                 $this->pdo = $link;
  23.             }
  24.             catch (PDOException $e)
  25.             {
  26.                 die ("Database connection error: " . $e->getMessage());
  27.             }
  28.         }
  29.     }
  30.  
  31.     public function select($table, $data = array())
  32.     {
  33.         $sql  = 'SELECT ';
  34.         $sql .= array_key_exists("select", $data) ? $data['select'] : '*';
  35.         $sql .= ' FROM ' . $table;
  36.  
  37.         if (array_key_exists("where", $data))
  38.         {
  39.             $sql .= ' WHERE ';
  40.             $i = 0;
  41.  
  42.             foreach ($data['where'] as $key => $value)
  43.             {
  44.                 $add  = ($i > 0) ? ' ADD ' : '';
  45.                 $sql .= "$add" . "$key =: $key";
  46.                 $i++;
  47.             }
  48.         }
  49.  
  50.         if (array_key_exists("order_by", $data))
  51.         {
  52.             $sql .= ' ORDER BY '. $data['order_by'];
  53.         }
  54.  
  55.         if (array_key_exists("start", $data) && array_key_exists("limit", $data))
  56.         {
  57.             $sql .= ' LIMIT ' . $data['start'] . ',' . $data['limit'];
  58.         }
  59.         elseif (! array_key_exists("start", $data) && array_key_exists("limit", $data))
  60.         {
  61.             $sql .= ' LIMIT ' . $data['limit'];
  62.         }
  63.  
  64.         $query = $this->pdo->prepare($sql);
  65.  
  66.         if (array_key_exists("where", $data))
  67.         {
  68.             foreach ($data['where'] as $key => $value)
  69.             {
  70.                 $query->bindValue(':key', $value);
  71.             }
  72.         }
  73.  
  74.         $query->execute();
  75.     }
  76.    
  77.    
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement