@@ -112,6 +112,18 @@ class MysqliDb
112112 */
113113 protected $ isSubQuery = false ;
114114
115+ /**
116+ * Name of the auto increment column
117+ *
118+ */
119+ protected $ lastInsertId = null ;
120+
121+ /**
122+ * Column names for update when using onDuplicate method
123+ *
124+ */
125+ protected $ updateColumns = null ;
126+
115127 /**
116128 * Return type: 'Array' to return results as array, 'Object' as object
117129 * 'Json' as json string
@@ -550,6 +562,19 @@ public function where($whereProp, $whereValue = 'DBNULL', $operator = '=', $cond
550562 return $ this ;
551563 }
552564
565+ /**
566+ * This function store update column's name and column name of the
567+ * autoincrement column
568+ *
569+ * @param Array Variable with values
570+ * @param String Variable value
571+ */
572+ public function onDuplicate ($ updateColumns , $ lastInsertId = null )
573+ {
574+ $ this ->lastInsertId = $ lastInsertId ;
575+ $ this ->updateColumns = $ updateColumns ;
576+ }
577+
553578 /**
554579 * This method allows you to specify multiple (method chaining optional) OR WHERE statements for SQL queries.
555580 *
@@ -779,6 +804,31 @@ private function _buildInsert ($tableName, $insertData, $operation)
779804 return true ;
780805 }
781806
807+ /**
808+ * Helper function to add variables into the query statement
809+ *
810+ * @param Array Variable with values
811+ */
812+ protected function _buildDuplicate ($ tableData )
813+ {
814+ if (is_array ($ this ->updateColumns ) && !empty ($ this ->updateColumns )) {
815+ $ this ->_query .= " on duplicate key update " ;
816+ if ($ this ->lastInsertId ) {
817+ $ this ->_lastQuery .= $ this ->lastInsertId ."=LAST_INSERT_ID( " .$ this ->lastInsertId ."), " ;
818+ $ this ->lastInsertId = null ;
819+ }
820+
821+ foreach ($ this ->updateColumns as $ value ) {
822+ $ this ->_bindParam ($ tableData [$ value ]);
823+ $ this ->_query .= "` " . $ value . "` = ?, " ;
824+ }
825+
826+ $ this ->_query = rtrim ($ this ->_query , ', ' );
827+ $ this ->lastInsertId = null ;
828+ $ this ->updateColumns = null ;
829+ }
830+ }
831+
782832 /**
783833 * Abstraction method that will compile the WHERE statement,
784834 * any passed update data, and the desired rows.
@@ -798,6 +848,7 @@ protected function _buildQuery($numRows = null, $tableData = null)
798848 $ this ->_buildGroupBy ();
799849 $ this ->_buildOrderBy ();
800850 $ this ->_buildLimit ($ numRows );
851+ $ this ->_buildDuplicate ($ tableData );
801852
802853 $ this ->_lastQuery = $ this ->replacePlaceHolders ($ this ->_query , $ this ->_bindParams );
803854
0 commit comments