Skip to content

Instantly share code, notes, and snippets.

@scottmac
Created November 7, 2010 21:09
Show Gist options
  • Save scottmac/666844 to your computer and use it in GitHub Desktop.
Save scottmac/666844 to your computer and use it in GitHub Desktop.
<?php
class DatabaseStatementBase extends PDOStatement {
public $dbh;
protected function __construct($dbh) {
$this->dbh = $dbh;
$this->setFetchMode(PDO::FETCH_OBJ);
}
public function fetchAllKeyed($key_index = 0, $value_index = 1) {
$return = array();
$this->setFetchMode(PDO::FETCH_NUM);
foreach ($this AS $record) {
$return[$record[$key_index]] = $record[$value_index];
}
return $return;
}
}
class DatabaseConnection extends PDO {
function __construct($dsn, $username, $password, $driver_options = array())
{
parent::__construct($dsn, $username, $password, $driver_options);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS,
array('DatabaseStatementBase', array($this)));
}
}
$pdo = new DatabaseConnection('sqlite::memory:', '', '');
$pdo->exec('CREATE TABLE foo (bar STRING)');
$pdo->exec("INSERT INTO foo VALUES ('ABC')");
$pdo->exec("INSERT INTO foo VALUES ('DEF')");
$result = $pdo->query("SELECT ROWID, bar FROM foo");
var_dump($result->fetchAllKeyed());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment