Skip to content

Instantly share code, notes, and snippets.

@MaikuDev
Forked from luckyshot/db.php
Last active September 6, 2015 08:16
Show Gist options
  • Save MaikuDev/ba4a24839e8ebdb0d471 to your computer and use it in GitHub Desktop.
Save MaikuDev/ba4a24839e8ebdb0d471 to your computer and use it in GitHub Desktop.
PHP/MySQL (PDO) method with named parameters
<?php
/*
PHP/MySQL (PDO) method with named parameters
---------------------------------------------
https://gist.github.com/luckyshot/9477105
define("MYSQL_SERVER", "localhost");
define("MYSQL_USER", "root");
define("MYSQL_PASS", "root");
define("MYSQL_DATABASE", "database");
$db = new DB(MYSQL_USER, MYSQL_PASS, MYSQL_DATABASE);
$select = $this->db->select("SELECT * FROM items WHERE id = :id LIMIT 1")
->bind(':id', $id)
->single();
$insert = $this->db->query("INSERT INTO items SET
aaa = :aaa,
bbb = :bbb")
->bind(':aaa', $aaa )
->bind(':bbb', $bbb )
->insert();
$update = $this->db->query("UPDATE items SET
aaa = :aaa
WHERE id = :id
LIMIT 1;")
->bind(':aaa', $aaa )
->bind(':id', $data['id'])
->execute();
$delete = $this->db->query("DELETE FROM items
WHERE id = :id
LIMIT 1;")
->bind(':id', $data['id'])
->execute();
*/
class DB {
private $dbh;
private $stmt;
public function __construct($user, $pass, $dbname) {
$this->dbh = new PDO(
"mysql:host=localhost;dbname=$dbname",
$user,
$pass,
array( PDO::ATTR_PERSISTENT => true )
);
$this->query("SET NAMES 'utf8';");
$this->execute();
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
return $this;
}
public function bind($pos, $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($pos, $value, $type);
return $this;
}
public function execute() {
return $this->stmt->execute();
}
// Same as execute() but returns ID
public function insert() {
$this->stmt->execute();
return $this->dbh->lastInsertId();
}
public function resultset() {
$this->execute();
return $this->stmt->fetchAll();
}
public function single() {
$this->execute();
return $this->stmt->fetch();
}
}
// A clone of DB to help in debugging
class DBdebug {
private $q;
public function query($q) {
$this->q = $q;
return $this;
}
public function bind($what, $with, $type = null) {
if (is_int($with)) {
$this->q = str_replace($what, $with, $this->q);
}else{
$this->q = str_replace($what, "'".$with."'", $this->q);
}
return $this;
}
public function execute() {
return $this->q;
}
public function insert() {
return $this->q;
}
public function resultset() {
return $this->q;
}
public function single() {
return $this->q;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment