InsertQuery из cms

This commit is contained in:
Anatoly 2017-02-09 11:07:18 +03:00
parent e2f5ecdbca
commit 5089a652eb

View file

@ -18,6 +18,9 @@ class Database extends PDO
return $this->dsn; return $this->dsn;
} }
public function isPostgres(){
return ($this->dsn["phptype"] == "pgsql");
}
/** /**
* Создает соединение с базой данных * Создает соединение с базой данных
*/ */
@ -77,13 +80,55 @@ class Database extends PDO
return $x . "=" . $this->quote($y); 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 запрос * Создает 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)) $prep = $this->prepareValues($values);
. ") VALUES (" . implode(",", array_map(array($this, 'quote'), array_values($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'];
}
}
} }
/** /**