Last active
November 9, 2016 06:48
-
-
Save nasrulhazim/ebd05b95e10ad7dd062d41565b3004ed to your computer and use it in GitHub Desktop.
Simple PDO Wrapper
This file contains hidden or 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 | |
namespace App\Database; | |
use \PDO; | |
class Connection | |
{ | |
private $conn; | |
private $database; | |
private $stmt; | |
public function __construct($host, $database, $username, $password) | |
{ | |
// Set DSN | |
$dsn = 'mysql:host=' . $host . ';dbname=' . $database; | |
// Set options | |
$options = array( | |
PDO::ATTR_PERSISTENT => true, | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |
); | |
// Create a new PDO instanace | |
try { | |
$this->conn = new PDO($dsn, $username, $password, $options); | |
} catch (PDOException $e) { | |
$this->error = $e->getMessage(); | |
} | |
} | |
public function query($query) | |
{ | |
$this->stmt = $this->conn->prepare($query); | |
return $this; | |
} | |
public function bind($param, $value, $type = null) | |
{ | |
if (is_null($type)) { | |
switch (true) { | |
case is_int($value): | |
$type = PDO::PARAM_INT; | |
break; | |
case is_bool($value): | |
$type = PDO::PARAM_BOOL; | |
break; | |
case is_null($value): | |
$type = PDO::PARAM_NULL; | |
break; | |
default: | |
$type = PDO::PARAM_STR; | |
} | |
} | |
$this->stmt->bindValue($param, $value, $type); | |
return $this; | |
} | |
public function execute() | |
{ | |
return $this->stmt->execute(); | |
} | |
public function resultset() | |
{ | |
$this->execute(); | |
return $this->stmt->fetchAll(PDO::FETCH_ASSOC); | |
} | |
public function single() | |
{ | |
$this->execute(); | |
return $this->stmt->fetch(PDO::FETCH_ASSOC); | |
} | |
public function rowCount() | |
{ | |
return $this->stmt->rowCount(); | |
} | |
public function lastInsertId() | |
{ | |
return $this->conn->lastInsertId(); | |
} | |
public function beginTransaction() | |
{ | |
return $this->conn->beginTransaction(); | |
} | |
public function endTransaction() | |
{ | |
return $this->conn->commit(); | |
} | |
public function cancelTransaction() | |
{ | |
return $this->conn->rollBack(); | |
} | |
public function debugDumpParams() | |
{ | |
return $this->stmt->debugDumpParams(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
Sample Output