Skip to content

Instantly share code, notes, and snippets.

@thoriqmacto
Created October 30, 2015 09:13
Show Gist options
  • Save thoriqmacto/cce63828612848c1919a to your computer and use it in GitHub Desktop.
Save thoriqmacto/cce63828612848c1919a to your computer and use it in GitHub Desktop.
[PHP] Data Access Object Pattern Example
<?php
abstract class baseDAO{
private $__connection;
public function __construct(){
$this->_connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE);
}
private function __connectToDB($user, $pass, $host, $database){
$this->__connection = mysql_connect($host, $user, $pass);
mysql_select_db($database, $this->__connection);
}
public function fetch($value, $key = NULL){
if (is_null($key)){
$key = $this- > primaryKey;
}
$sql = "select * from {$this->tableName} where {$key}='{$value}'";
$results = mysql_query($sql, $this- >__connection);
$rows = array();
while ($result = mysql_fetch_array($results)) {
$rows[] = $result;
}
return $rows;
}
public function update($keyedArray){
$sql = "update {$this->tableName} set ";
$updates = array();
foreach ($keyedArray as $column=> $value) {
$updates[] = "{$column}='{$value}'";
}
$sql .= implode(',', $updates);
$sql .= "where {$this->primaryKey}='{$keyedArray[$this->primaryKey]}'";
mysql_query($sql, $this->__connection);
}
}
class userDAO extends baseDAO{
protected $_tableName = 'userTable';
protected $_primaryKey = 'id';
public function getUserByFirstName($name){
$result = $this->fetch($name, 'firstName');
return $result;
}
}
define('DB_USER', 'user');
define('DB_PASS', 'pass');
define('DB_HOST', 'localhost');
define('DB_DATABASE', 'test');
$user = new userDAO();
$userDetailsArray = $user->fetch(1);
$updates = array('id' => 1, 'firstName' => 'aaron');
$user->update($updates);
$allAarons = $user->getUserByFirstName('aaron');
?>
@ddruganov
Copy link

Isnt this just active record?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment