Created
February 10, 2012 19:49
-
-
Save alexburner/1792187 to your computer and use it in GitHub Desktop.
PHP PDO helper 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
class PDOwrapper { | |
// | |
// VARIABLES | |
private $db = array( | |
'host' => null, | |
'name' => null, | |
'user' => null, | |
'pass' => null, | |
'pdo' => null | |
); | |
public $pdo; | |
// | |
// CONFIG | |
private function buildPDO() { | |
$this->pdo = new PDO( | |
'mysql:host=' . $this->db[ 'host' ] . ';' . | |
'dbname=' . $this->db[ 'name' ], | |
$this->db[ 'user' ], | |
$this->db[ 'pass' ] | |
); | |
} | |
function __construct( $host, $name, $user, $pass ) { | |
$this->db[ 'host' ] = $host; | |
$this->db[ 'name' ] = $name; | |
$this->db[ 'user' ] = $user; | |
$this->db[ 'pass' ] = $pass; | |
$this->buildPDO(); | |
} | |
public function setConfig( $args ) { | |
$keys = array_keys( $db ); | |
foreach ( $keys as $key ) if ( isset( $args[ $key ] ) ) $this->db[ $key ] = $args[ $key ]; | |
$this->buildPDO(); | |
} | |
// | |
// INSERT | |
private function insert( $table, $columns, $rowdicts ) { | |
// columns = array of row columns | |
// rowdicts = array of dictionaries | |
$placeholders = ''; | |
foreach ($columns as $column) $placeholders = $placeholders . $column . ' = ?, '; | |
$placeholders = substr( $placeholders, 0, -2 ); | |
$stmt = $this->pdo->prepare( 'INSERT INTO ' . $table . ' SET ' . $placeholders ); | |
foreach( $rowdicts as $rowdict ) { | |
$vcount = 0; | |
foreach( $rowdict as $value ) { | |
$vcount++; | |
$stmt->bindValue( $vcount, $value ); | |
} | |
$stmt->execute(); | |
} | |
} | |
public function insertRows( $table, $rowdicts ) { | |
$columns = array_keys( $rowdicts[ 0 ] ); | |
$this->insert( $table, $columns, $rowdicts ); | |
} | |
public function insertRow( $table, $rowdict ) { | |
$columns = array_keys( $rowdict ); | |
$this->insert( $table, $columns, array( $rowdict ) ); | |
} | |
} | |
$db = new PDOwrapper( 'localhost', 'practice','root','root' ); | |
$db->insertRow( 'Posts', array( 'title' => 'FINGERS CROSSED', 'content' => 'HMMMMMMMMMM' ) ); | |
$db->insertRows( 'Posts', array( | |
array( 'title' => 'FINGERS CROSSED AGAIN', 'content' => 'HRMMM' ), | |
array( 'title' => 'OH BOY GOSH', 'content' => 'GEEEEEEEEE' ), | |
array( 'title' => 'I LIKE TURTLES', 'content' => 'TEE HEEEEEEEE' ) | |
) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment