Advertisement
MargieN

Untitled

Oct 30th, 2015
3,203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. G<?php
  2.  
  3. abstract class baseDAO{
  4.     private $__connection;
  5.    
  6.     public function __construct(){
  7.         $this->_connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE);
  8.     }
  9.    
  10.     private function __connectToDB($user, $pass, $host, $database){
  11.         $this->__connection = mysql_connect($host, $user, $pass);
  12.         mysql_select_db($database, $this->__connection);
  13.     }
  14.    
  15.     public function fetch($value, $key = NULL){
  16.         if (is_null($key)){
  17.             $key = $this- > primaryKey;
  18.         }
  19.    
  20.         $sql = "select * from {$this->tableName} where {$key}='{$value}'";
  21.         $results = mysql_query($sql, $this- >__connection);
  22.         $rows = array();
  23.        
  24.         while ($result = mysql_fetch_array($results)) {
  25.             $rows[] = $result;
  26.         }
  27.         return $rows;
  28.     }
  29.    
  30.     public function update($keyedArray){
  31.         $sql = "update {$this->tableName} set ";
  32.         $updates = array();
  33.        
  34.         foreach ($keyedArray as $column=> $value) {
  35.             $updates[] = "{$column}='{$value}'";
  36.         }
  37.        
  38.         $sql .= implode(',', $updates);
  39.         $sql .= "where {$this->primaryKey}='{$keyedArray[$this->primaryKey]}'";
  40.         mysql_query($sql, $this->__connection);
  41.     }
  42. }
  43.  
  44. class userDAO extends baseDAO{
  45.     protected $_tableName = 'userTable';
  46.     protected $_primaryKey = 'id';
  47.    
  48.     public function getUserByFirstName($name){
  49.         $result = $this->fetch($name, 'firstName');
  50.         return $result;
  51.     }
  52. }
  53.  
  54.  
  55. define('DB_USER', 'user');
  56. define('DB_PASS', 'pass');
  57. define('DB_HOST', 'localhost');
  58. define('DB_DATABASE', 'test');
  59.  
  60. $user = new userDAO();
  61. $userDetailsArray = $user->fetch(1);
  62. $updates = array('id' => 1, 'firstName' => 'aaron');
  63. $user->update($updates);
  64. $allAarons = $user->getUserByFirstName('aaron');
  65. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement