Skip to content

Instantly share code, notes, and snippets.

@matiasa18
Created April 23, 2012 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matiasa18/2467991 to your computer and use it in GitHub Desktop.
Save matiasa18/2467991 to your computer and use it in GitHub Desktop.
PDO Handler
<?php
class Dbh {
private $db;
private $querys = array();
private $result;
private $log;
public function __construct( $db ) {
$this -> db = $db;
}
public function bindParam($param, $value, $type = PDO::PARAM_STR) {
if( $this -> log ) {
echo 'Setted param: "'.$param.'" as "'.$value.'" ('.$type.') <br>';
}
$this -> result -> bindParam($param, $value, $type);
}
public function prepare($query, $log = false) {
$this -> log = $log;
if( $this -> log ) {
echo 'Preparing Query (' . $query. ')<br>';
}
$this -> result = $this -> db -> prepare($query);
}
public function execute() {
// $this -> querys [] = $query;
if ( $this -> log ) {
echo 'Executing last Query<br>';
}
try {
$this -> result -> execute();
}catch(PDOException $e) {
bony :: getInstance() -> throwException ($e);
}
}
public function fetchAll($type = PDO::FETCH_ASSOC) {
return $this -> result -> fetchAll ($type);
}
public function fetch($type = PDO::FETCH_ASSOC) {
return $this -> result -> fetch ($type);
}
public function lastId() {
return $this -> db -> lastInsertId();
}
}
?>
<?php
require_once('dbhandler.php');
try{
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db -> exec('SET CHARACTER SET utf8');
} catch( Exception $e ) {
die($e);
}
// Generate the new dbhandler class
$dbh = new Dbh( $db );
// Second param is true so we can log.
$dbh -> prepare ('SELECT * FROM test WHERE id=:id', true);
$dbh -> bindParam (':id', 2, PDO::PARAM_INT);
$dbh -> execute();
$result = $dbh -> fetch(PDO::FETCH_ASSOC);
var_dump($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment