Created
June 7, 2014 12:56
-
-
Save ruliarmando/8dda4c5c30aef73ea92d to your computer and use it in GitHub Desktop.
PDO based Database Wrapper class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Db | |
{ | |
private $conn = null; | |
private $dsn; | |
private $user; | |
private $password; | |
public function __construct($dsn, $user, $password) | |
{ | |
$this->dsn = $dsn; | |
$this->user = $user; | |
$this->password = $password; | |
} | |
private function connect() | |
{ | |
if(!isset($this->conn)){ | |
try{ | |
$this->conn = new PDO($this->dsn, $this->user, $this->password); | |
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); | |
}catch(PDOException $e){ | |
$this->disconnect(); | |
echo $e->getMessage(); | |
} | |
} | |
return $this->conn; | |
} | |
public function disconnect(){ | |
$this->conn = null; | |
} | |
public function execute($sql, $params = null) | |
{ | |
try{ | |
$conn = $this->connect(); | |
$stmt = $conn->prepare($sql); | |
$stmt->execute($params); | |
}catch(PDOException $e){ | |
$this->disconnect(); | |
echo $e->getMessage(); | |
} | |
} | |
public function all($sql, $params = null, $fetch_style = PDO::FETCH_OBJ) | |
{ | |
$result = null; | |
try{ | |
$conn = $this->connect(); | |
$stmt = $conn->prepare($sql); | |
$stmt->execute($params); | |
$result = $stmt->fetchAll($fetch_style); | |
}catch(PDOException $e){ | |
$this->disconnect(); | |
echo $e->getMessage(); | |
} | |
return $result; | |
} | |
public function row($sql, $params = null, $fetch_style = PDO::FETCH_OBJ) | |
{ | |
$result = null; | |
try{ | |
$conn = $this->connect($conn_name); | |
$stmt = $conn->prepare($sql); | |
$stmt->execute($params); | |
$result = $stmt->fetch($fetch_style); | |
}catch(PDOException $e){ | |
$this->disconnect(); | |
echo $e->getMessage(); | |
} | |
return $result; | |
} | |
public function one($sql, $params = null) | |
{ | |
$result = null; | |
try{ | |
$conn = $this->connect(); | |
$stmt = $conn->prepare($sql); | |
$stmt->execute($params); | |
$result = $stmt->fetch(PDO::FETCH_NUM); | |
$result = $result[0]; | |
}catch(PDOException $e){ | |
$this->disconnect(); | |
echo $e->getMessage(); | |
} | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment