Created
November 7, 2010 21:09
-
-
Save scottmac/666844 to your computer and use it in GitHub Desktop.
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
<?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