Add upsert function
This commit is contained in:
23
inc/Db.php
23
inc/Db.php
@@ -483,6 +483,29 @@ class Db extends PhpObject
|
||||
return $iTableId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike insertUpdateRow, this function depends on the table defined UNIQUE KEY
|
||||
* and not on the custom-defined $asKeys table
|
||||
*/
|
||||
public function upsertRow($sTableName, $asData, $asUpdateFields)
|
||||
{
|
||||
$this->cleanSql($sTableName);
|
||||
$this->cleanSql($asData);
|
||||
$this->cleanSql($asUpdateFields);
|
||||
|
||||
$asQueryValues = $this->addQuotes($asData);
|
||||
$asUpdateValues = array_intersect_key($asData, array_flip($asUpdateFields));
|
||||
|
||||
$sQuery =
|
||||
"INSERT INTO ".$sTableName." (`".implode("`, `", array_keys($asQueryValues))."`) ".
|
||||
"VALUES (".implode(", ", $asQueryValues).") ".
|
||||
"ON DUPLICATE KEY UPDATE ".$this->implodeAll($asUpdateValues, " = ", ", ");
|
||||
|
||||
die($sQuery);
|
||||
|
||||
return $this->setQuery($sQuery)?$this->getLastId():0;
|
||||
}
|
||||
|
||||
public function selectInsert($sTableName, $asData, $asKeys=array())
|
||||
{
|
||||
return $this->insertUpdateRow($sTableName, $asData, $asKeys, false);
|
||||
|
||||
Reference in New Issue
Block a user