Gdn_SQLDriver::replace PHP Method

replace() public method

Inserts or updates values in the table depending on whether they are already there.
public replace ( string $Table = '', array $Set = null, array $Where, $CheckExisting = false )
$Table string The name of the table to insert/update.
$Set array The columns to update.
$Where array The columns to find the row to update. If a row is not found then one is inserted and the items in this array are merged with $Set.
    public function replace($Table = '', $Set = null, $Where, $CheckExisting = false)
    {
        if (count($this->_Sets) > 0) {
            foreach ($this->_Sets as $Key => $Value) {
                if (array_key_exists($Value, $this->_NamedParameters)) {
                    $Set[$Key] = $this->_NamedParameters[$Value];
                    unset($this->_NamedParameters[$Value]);
                } else {
                    $Set[$Key] = $Value;
                }
            }
            $this->_Sets = array();
        }
        // Check to see if there is a row in the table like this.
        if ($CheckExisting) {
            $Row = $this->getWhere($Table, $Where)->firstRow(DATASET_TYPE_ARRAY);
            $Update = false;
            if ($Row) {
                $Update = true;
                foreach ($Set as $Key => $Value) {
                    unset($Set[$Key]);
                    $Key = trim($Key, '`');
                    if (!$this->CaptureModifications && !array_key_exists($Key, $Row)) {
                        continue;
                    }
                    if (in_array($Key, array('DateInserted', 'InsertUserID', 'DateUpdated', 'UpdateUserID'))) {
                        continue;
                    }
                    // We are assuming here that if the existing record doesn't contain the column then it's just been added.
                    if (preg_match('/^`(.+)`$/', $Value, $Matches)) {
                        if (!array_key_exists($Key, $Row) || $Row[$Key] != $Row[$Matches[1]]) {
                            $this->set('`' . $Key . '`', $Value, false);
                        }
                    } elseif (!array_key_exists($Key, $Row) || $Row[$Key] != $Value) {
                        $this->set('`' . $Key . '`', $Value);
                    }
                }
                if (count($this->_Sets) == 0) {
                    $this->reset();
                    return;
                }
            }
        } else {
            $Count = $this->getCount($Table, $Where);
            $Update = $Count > 0;
        }
        if ($Update) {
            // Update the table.
            $this->put($Table, $Set, $Where);
        } else {
            // Insert the table.
            $Set = array_merge($Set, $Where);
            $this->insert($Table, $Set);
        }
    }