InsertQuery из cms
This commit is contained in:
parent
e2f5ecdbca
commit
5089a652eb
1 changed files with 48 additions and 3 deletions
|
|
@ -18,6 +18,9 @@ class Database extends PDO
|
|||
return $this->dsn;
|
||||
}
|
||||
|
||||
public function isPostgres(){
|
||||
return ($this->dsn["phptype"] == "pgsql");
|
||||
}
|
||||
/**
|
||||
* Создает соединение с базой данных
|
||||
*/
|
||||
|
|
@ -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'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue