/** * Inserts a new row and returns the id or false if failed. * @param string [string] $columns * @param string [string]|string $duplicateKey Can have the value "ignore" or list of columns to update * @param string[] $params Optional params in case that string is sent to duplicate key * @return int|boolean */ public function insert($columns, $duplicateKey = null, $params = []) { if (is_string($duplicateKey) && 'ignore' == strtolower($duplicateKey)) { $q = "INSERT IGNORE INTO {$this->table} "; } else { $q = "INSERT INTO {$this->table} "; } $cols = array(); $vals = array(); $this->params = $params; foreach ($columns as $name => $value) { $cols[] = '`' . $name . '`'; $vals[] = ":{$name}"; $this->params[":{$name}"] = $value; } $q .= "(" . implode(", ", $cols) . ") VALUES (" . implode(", ", $vals) . ")"; if (is_array($duplicateKey) && count($duplicateKey)) { $q .= " ON DUPLICATE KEY UPDATE "; $updates = []; foreach ($duplicateKey as $column => $value) { $updates[] = "`{$column}` = :dp_{$column}"; $this->params[':dp_' . $column] = $value; } $q .= implode(", ", $updates); } elseif ($duplicateKey && is_string($duplicateKey) && 'ignore' != strtolower($duplicateKey)) { $q .= " ON DUPLICATE KEY UPDATE " . $duplicateKey; } if ($this->connection->execQuery($q, $this->params)) { return $this->connection->lastInsertId() ? $this->connection->lastInsertId() : true; } else { return false; } }
/** * It will create a copy of the current element in DB. This Object will be the new copy just inserted. * @param bool $validate * @return bool|int */ public function saveAsNew($validate = true) { if ($validate && !$this->validate()) { return false; } if (!is_string($this->_pk)) { $this->error("Can't duplicate rows in tables with multiple primary keys!"); return false; } $originalBackup = $this->_originalPk; unset($this->_attributes[$this->_pk]); $this->_originalPk = $this->_db->table($this->_tableName)->insert($this->_attributes); if (!$this->_originalPk) { $this->_originalPk = $originalBackup; return false; // error when trying to insert; } $this->reload(); return $this->_db->lastInsertId(); }