Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Обертка над БД
- *
- * @author Fragster
- */
- class DB extends PDO {
- /**
- *
- * @var DB
- */
- private static $singleton;
- private $engine;
- private $host;
- private $database;
- private $user;
- private $pass;
- public function __construct() {
- $this->engine = 'mysql';
- $this->host = Config::$db_host;
- $this->database = Config::$db_database;
- $this->user = Config::$db_user;
- $this->pass = Config::$db_password;
- $dns = $this->engine . ':dbname=' . $this->database . ";host=" . $this->host;
- parent::__construct($dns, $this->user, $this->pass);
- $this->exec("SET NAMES utf8");
- $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- }
- /**
- *
- * @return DB
- */
- static function Init() {
- if (!self::$singleton) {
- self::$singleton = new DB;
- }
- return self::$singleton;
- }
- public function arrayPrepare($query, array $input_parameters) {
- $query = str_replace("\n", "", $query);
- $params = array();
- foreach ($input_parameters as $key => $value) {
- if (is_array($value)) {
- $implode = '';
- $delim = '';
- foreach ($value as $valueKey => $valueValue) {
- $params[$key . '_' . $valueKey] = $valueValue;
- $implode.= $delim . $key . '_' . $valueKey;
- $delim = ', ';
- }
- $query = str_replace($key, $implode, $query);
- } else {
- $params[$key] = $value;
- }
- }
- try {
- $statement = $this->prepare($query);
- } catch (Exception $exc) {
- throw new Exception($query."\n".$this->errorInfo());
- }
- //echo "$query\n";
- foreach ($params as $key => $value) {
- //echo "bind $key => $value\n";
- $statement->bindValue($key, $value)."\n";
- }
- return $statement;
- }
- public function multiInsert($query, array $insert_array) {
- $query = str_replace("\n", "", $query);
- $query1 = array();
- preg_match('/.*values\s*/im', $query, $query1);
- $query1 = $query1[0];
- $placeholders = array();
- preg_match_all('/:\w+/im', $query, $placeholders);
- $placeholders = $placeholders[0];
- $rowDelim = '';
- foreach ($insert_array as $key => $value) {
- $query1.= $rowDelim . '(';
- $rowDelim = ', ';
- $fieldDelim = '';
- foreach ($placeholders as $placeholder) {
- $query1.= $fieldDelim . $placeholder . '_' . $key;
- $fieldDelim = ', ';
- }
- $query1.= ')';
- }
- try {
- $statement = $this->prepare($query1);
- } catch (Exception $exc) {
- throw new Exception($query1."\n".$this->errorInfo());
- }
- foreach ($insert_array as $key => $value) {
- foreach ($placeholders as $placeholder) {
- $var = $value[$placeholder];
- $statement->bindValue($placeholder . '_' . $key, $var);
- }
- }
- $statement->execute();
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement