/** * Saves the current state of all data in this object to database (INSERT * or UPDATE). * * If the class has a primary key column "id" it will be auto-populated * on INSERT (for use with AUTO_INCREMENT columns). */ public function save() { $values = array(); foreach ($this->_columns as $property) { $values[$property] = $this->{$property}; } if ($this->_exists) { if (count($values) > 0) { $primary_values = array(); foreach (static::$primary_columns as $primary_column) { if (array_key_exists($primary_column, $values)) { $primary_values[$primary_column] = $values[$primary_column]; unset($values[$primary_column]); } } // If a table only consists of primary columns, we might end up with // no values to update. if (count($values) > 0) { self::build('update', function ($qb) use($values, $primary_values) { $qb->set($values); foreach ($primary_values as $columns => $value) { $qb->where($columns, '=', $value); } })->prepareAndExecute(); } } } else { self::build('insert', function ($qb) use($values) { $qb->values($values); })->prepareAndExecute(); if (!$this->_exists) { $this->_exists = true; if (in_array('id', static::$primary_columns)) { $this->id = PDO::getInstance()->lastInsertId(); } } } }