<?php
class dao
{
private $db = NULL;
private $connection_string = NULL;
private $db_type = DB_TYPE;
private $db_path = DB_PATH;
private $db_host = DB_HOST;
private $db_user = DB_USER;
private $db_pass = DB_PASS;
private $db_name = DB_NAME;
private $con = false;
public function __construct($db_user = DB_USER, $db_pass = DB_PASS, $db_name = DB_NAME, $db_type = 'mysql', $db_path = DB_PATH, $db_host = 'localhost') {
$this->db_host = $db_host;
$this->db_user = $db_user;
$this->db_pass = $db_pass;
$this->db_name = $db_name;
$this->db_path = $db_path;
$this->db_type = $db_type;
switch($this->db_type){
case "mysql":
$this->connection_string = "mysql:host=".$db_host.";dbname=".$db_name;
break;
case "sqlite":
$this->connection_string = "sqlite:".$db_path;
break;
case "oracle":
$this->connection_string = "OCI:dbname=".$db_name.";charset=UTF-8";
break;
case "dblib":
$this->connection_string = "dblib:host=".$db_host.";dbname=".$db_name;
break;
case "postgresql":
$this->connection_string = "pgsql:host=".$db_host." dbname=".$db_name;
break;
}
return $this;
}
public function connect() {
// cek koneksi apa udah tersambung atau belum
if(!$this->con) {
try {
$this->db = new PDO($this->connection_string,$this->db_user, $this->db_pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con = true;
return $this->con;
} catch (PDOException $e) {
return $e->getMessage();
}
} else {
return true; // kalo udah konek sebelumnya, diem aja
}
}
public function disconnect() {
if($this->con) {
unset($this->db);$this->con = false;
return true;
}
}
public function select($table, $rows = '*', $where = null, $order = null) {
if($this->tableExists($table)) {
$q = 'SELECT '.$rows.' FROM '.$table;
if($where != null)
$q .= ' WHERE '.$where;
if($order != null)
$q .= ' ORDER BY '.$order;
$this->numResults = null;
try {
$sql = $this->db->prepare($q);
$sql->execute();
$this->result = $sql->fetchAll(PDO::FETCH_ASSOC);
$this->numResults = count($this->result);
$this->numResults === 0 ? $this->result = null : true ;
return true;
} catch (PDOException $e) {
return $e->getMessage().''.$e->getTraceAsString().'';
}
}
}
public function getResult() {
return $this->result;
}
}
?>
Post a Comment
Diharapkan jangan berkata-kata yang kurang enak, karena itu akan mengganggu orang yang membacanya, dan berikan saran anda jika blog kami masih kurang berkenan.
terimakasih,
Admin