Skip to content

Instantly share code, notes, and snippets.

@ruliarmando
Created June 7, 2014 12:56
Show Gist options
  • Save ruliarmando/8dda4c5c30aef73ea92d to your computer and use it in GitHub Desktop.
Save ruliarmando/8dda4c5c30aef73ea92d to your computer and use it in GitHub Desktop.
PDO based Database Wrapper class
<?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