From 3b5808523d195912092753b5c75af74fada49bc9 Mon Sep 17 00:00:00 2001 From: Franzz Date: Sat, 25 May 2024 12:20:03 +0200 Subject: [PATCH] Add upsert function --- inc/Db.php | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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);