Advertisement
DanielKoehler

Untitled

Nov 18th, 2013
1,189
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. class database{
  3.     var $conn;
  4.     function __construct()
  5.     {
  6.         try{
  7.             $this->conn = new PDO('mysql:host=ephesus.cs.cf.ac.uk;dbname=c1340154;','c1340154', 'caffenero');
  8.             $this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);   
  9.         } catch(PDOException $e){
  10.             die($e->getMessage());
  11.         }
  12.     }
  13.  
  14.     function prep_keys($data = array())
  15.     {
  16.         if(is_array($data) &&  !empty($data)){
  17.             foreach($data as $key => $value){
  18.                 if($key{0} != ':'){
  19.                     $data[':'.$key] = $value;
  20.                     unset($data[$key]);
  21.                 }
  22.             }
  23.             return $data;
  24.         }
  25.         return array($data);
  26.     }
  27.  
  28.     function select($sql, $data = array())
  29.     {
  30.         $stmt = $this->conn->prepare($sql);
  31.         $stmt->execute($data);
  32.         return $stmt->fetchAll(PDO::FETCH_ASSOC);
  33.     }
  34.  
  35.     function insert($table, $data)
  36.     {
  37.         foreach($data as $key => $value)
  38.         {
  39.             $columns[] = $key;
  40.         }
  41.         $stmt = $this->conn->prepare("INSERT INTO `$table` (`".implode('`, `', $columns)."`) VALUES (".implode(', ', array_keys($this->prep_keys($data))).")");
  42.         $stmt->execute($this->prep_keys($data));
  43.         return $this->conn->lastInsertId();
  44.     }
  45.  
  46.     function update($table, $data,$where_column,$ids)
  47.     {
  48.         $state = true;
  49.         foreach ($data as $key => $value)
  50.         {
  51.             $set_data[] = "`$key` = :" . $key;
  52.         }
  53.  
  54.         $stmt = $this->conn->prepare("UPDATE `$table` SET ".implode(', ', $set_data)." WHERE `$where_column` = :whereid");
  55.  
  56.         foreach ($ids as $id) {
  57.             $data['whereid'] = $id;
  58.             $state = $stmt->execute($this->prep_keys($data));
  59.         }
  60.        
  61.         return $state;
  62.     }
  63.  
  64.     function delete($table,$where_column,$ids = array())
  65.     {
  66.         $stmt = $this->conn->prepare("DELETE FROM `$table` WHERE `$where_column` = :whereid");
  67.         foreach ($ids as $id) {
  68.             $data['whereid'] = $id;
  69.             $state = $stmt->execute($this->prep_keys($data));
  70.         }
  71.         return $stmt->execute();
  72.     }
  73.  
  74.     function force_disconect()
  75.     {
  76.         $this->conn = null;
  77.     }
  78.  
  79.     function __destruct()
  80.     {
  81.         $this->conn = null;
  82.     }
  83. }
Advertisement
RAW Paste Data Copied
Advertisement