Last active
October 10, 2015 13:18
-
-
Save ajcrites/3695978 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 DB extends PDO { | |
public function __construct($dsn = null, $user = null, $pass = null) { | |
$dsn = $dsn !== null ? $dsn : "mysql:host=localhost;dbname=$_SERVER[DBNAME]"; | |
$user = $user !== null ? $user : $_SERVER['DBUSER']; | |
$pass = $pass !== null ? $pass : $_SERVER['DBPASS']; | |
parent::__construct($dsn, $user, $pass); | |
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} | |
public function query($query) { | |
$result = parent::query($query); | |
$result->setFetchMode(PDO::FETCH_OBJ); | |
return new DBST($result); | |
} | |
public function prepare($query, $options = array()) { | |
$result = parent::prepare($query, $options); | |
$result->setFetchMode(PDO::FETCH_OBJ); | |
return new DBST($result); | |
} | |
} | |
class DBST { | |
private $result; | |
public function __construct(PDOStatement $result) { | |
$this->result = $result; | |
} | |
public function execute() { | |
$args = array(); | |
foreach (func_get_args() as $arg) { | |
if (is_array($arg)) { | |
foreach ($arg as $a) { | |
$args[] = $a; | |
} | |
} | |
else { | |
$args[] = $arg; | |
} | |
} | |
$this->result->execute($args); | |
return $this; | |
} | |
public function fetch() { | |
$result = $this->result->fetch(); | |
return $result; | |
} | |
public function all() { | |
$rows = array(); | |
while ($row = $this->result->fetch()) { | |
$rows[] = $row; | |
} | |
return $rows; | |
} | |
public function rows() { | |
return $this->result->rowCount(); | |
} | |
} | |
$db = new DB; | |
$stmt = $db->prepare('SELECT col1 FROM t1 WHERE col2 = ? AND col3 = ?'); | |
//In line execute | |
//No array wrapper required for multiple unnamed parameters | |
while ($row = $stmt->execute('col2', 'col3')->fetch()) { | |
echo "$row->col1\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment