diff --git a/inc/Db.php b/inc/Db.php index f0efd79..fe8fe9c 100644 --- a/inc/Db.php +++ b/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);