diff --git a/core/database_pdo.php b/core/database_pdo.php index 0c7770c..f8db49c 100644 --- a/core/database_pdo.php +++ b/core/database_pdo.php @@ -18,6 +18,9 @@ class Database extends PDO return $this->dsn; } + public function isPostgres(){ + return ($this->dsn["phptype"] == "pgsql"); + } /** * Создает соединение с базой данных */ @@ -53,23 +56,23 @@ class Database extends PDO /** * Извлекает из базы все элементы по запросу */ - public function fetchAllArray($query) + public function fetchAllArray($query,$values=null) { $sth = $this->prepare($query); - $sth->setFetchMode(PDO::FETCH_ASSOC); - $sth->execute(); - return $sth->fetchAll(); + $prep = $this->prepareValues($values); + $sth->execute($prep); + return $sth->fetchAll(PDO::FETCH_ASSOC); } /** * Извлекает из базы первый элемент по запросу */ - public function fetchOneArray($query) + public function fetchOneArray($query,$values=null) { $sth = $this->prepare($query); - $sth->setFetchMode(PDO::FETCH_ASSOC); - $sth->execute(); - return $sth->fetch(); + $prep = $this->prepareValues($values); + $sth->execute($prep); + return $sth->fetch(PDO::FETCH_ASSOC); } private function assignQuote($x, $y) @@ -77,13 +80,55 @@ class Database extends PDO return $x . "=" . $this->quote($y); } + private function prepareValues($values) + { + if (!$values) { + return null; + } + $pg = $this->isPostgres(); + $prep = array(); + foreach ($values as $key => $value) { + $result = null; + if(is_bool($value)) { + if ($pg) { + $result = $value ? 'true' : 'false'; + } else { + $result = $value ? 1 : 0; + } + } else { + $result = $value; + } + $prep[":" . $key] = $result; + } + return $prep; + } /** * Создает INSERT запрос */ - function insertQuery($table, array $values) + function insertQuery($table, array $values, $return_id = false, $index = null) { - return $this->query("INSERT INTO $table (" . implode(",", array_keys($values)) - . ") VALUES (" . implode(",", array_map(array($this, 'quote'), array_values($values))) . ")"); + $prep = $this->prepareValues($values); + + $sql = "INSERT INTO $table (" . implode(",", array_keys($values)) + . ") VALUES (" . implode(",", array_keys($prep)). ")"; + + if($return_id){ + if ($this->isPostgres()){ + $sql = $sql." RETURNING $index"; + } + } + $stmt = $this->prepare($sql); + $stmt->setFetchMode(PDO::FETCH_ASSOC); + $stmt->execute($prep); + $result = $stmt->fetch(); + if ($return_id) { + if ($this->isPostgres()) { + return $result[$index]; + } else { + $result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()"); + return $result['lastid']; + } + } } /**