Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class DBConnectionFailure extends Exception {}
- class DB extends PDO {
- function __construct() {
- $dsn = 'mysql:dbname=' . DBConfig::DBNAME . ';host=' . DBConfig::HOST;
- try {
- parent::__construct($dsn, DBConfig::USER, DBConfig::PASSWORD);
- }
- catch (PDOException $e) {
- throw new DBConnectionFailure();
- }
- $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $this->exec('SET NAMES ' . DBConfig::CHARSET);
- }
- static function i() {
- static $instance;
- if (!$instance) {
- $instance = new self;
- }
- return $instance;
- }
- function quoteIndent($str) {
- return '`' . str_replace('`', '``', $str) . '`';
- }
- function getFullTableName($table) {
- return $this->quoteIndent(DBConfig::TABLE_PREFIX . $table);
- }
- function pQuery($sql, $params = null) {
- // подставляем преффиксы таблицам
- $sql = str_replace('?_', DBConfig::TABLE_PREFIX, $sql);
- $stmt = $this->prepare($sql);
- $stmt->execute($params);
- return $stmt;
- }
- function single() {
- $args = func_get_args();
- $stmt = call_user_func_array(array($this, 'pQuery'), $args);
- return $stmt->fetchColumn();
- }
- function row() {
- $args = func_get_args();
- $stmt = call_user_func_array(array($this, 'pQuery'), $args);
- return $stmt->fetch();
- }
- function rows() {
- $args = func_get_args();
- $stmt = call_user_func_array(array($this, 'pQuery'), $args);
- return $stmt->fetchAll();
- }
- function assoc() {
- $args = func_get_args();
- $stmt = call_user_func_array(array($this, 'pQuery'), $args);
- $res = $stmt->fetchAll(PDO::FETCH_NUM);
- if (!is_array($res)) {
- return $res;
- }
- $ret = array();
- $total = count($res);
- for ($i = 0; $i < $total; ++$i) {
- $ret[$res[$i][0]] = $res[$i][1];
- }
- return $ret;
- }
- function insert($table, $data) {
- $sql = 'INSERT INTO' . $this->getFullTableName($table);
- $values = array_values($data);
- if ($values != $data) {
- $keys = array_keys($data);
- $sql .= '(' . implode(',', array_map(array($this, 'quoteIndent'), $keys)) . ')';
- }
- $sql .= 'VALUES(' . implode(',', array_fill(0, count($data), '?')) . ')';
- $this->pQuery($sql, $values);
- return $this->lastInsertId();
- }
- function update($table, $id, $data) {
- $sql = 'UPDATE' . $this->getFullTableName($table) . ' SET ';
- $temp = array();
- foreach (array_keys($data) as $v) {
- $temp[] = $this->quoteIndent($v) . '=?';
- }
- $sql .= implode(',', $temp) . 'WHERE id=' . intval($id);
- $stmt = $this->pQuery($sql, array_values($data));
- return $stmt->rowCount();
- }
- function delete($table, $id) {
- $sql = 'DELETE FROM' . $this->getFullTableName($table) . ' WHERE id=' . intval($id);
- $stmt = $this->pQuery($sql);
- return $stmt->rowCount();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment