Example #1
0
 public function save()
 {
     $prepared = array();
     // prepare values
     foreach ($this->_data as $field => $value) {
         $fieldType = self::$_metadata[$field];
         $prepared[$field] = $this->_prepareValue($fieldType, $value);
     }
     // do the save (insert/update)
     if ($this->_isNew) {
         // insert
         $fields = array();
         $values = array();
         foreach ($prepared as $field => $preparedValue) {
             $fields[] = $field;
             $values[] = $preparedValue;
         }
         $fields = implode(", ", $fields);
         $values = implode(", ", $values);
         // prepare sql
         $sql = "INSERT INTO {$this->_table} ({$fields}) VALUES ({$values}) ";
         // execute
         $res = $this->_db->executeSQL($sql);
         if (!$res) {
             throw new ModelException("Invalid query - " . $this->_db->getError());
         }
         // update the pointer to primary key
         $this->_id = $this->_data[self::$_primaryField];
         if (is_null($this->_id)) {
             $this->_id = $this->lastInsertId();
         }
     } else {
         // update
         $updateSet = array();
         foreach ($prepared as $field => $preparedValue) {
             $updateSet[] = "{$field} = {$preparedValue}";
         }
         $updateSet = implode(", ", $updateSet);
         // prepare primary key
         $prim = self::$_primaryField;
         $preparedId = $this->_prepareValue(self::$_metadata[$prim], $this->_id);
         //prepare sql
         $sql = "UPDATE `{$this->_table}` SET {$updateSet} WHERE `{$prim}` = {$preparedId}";
         // execute
         $res = $this->_db->executeSQL($sql);
         if (!$res) {
             throw new ModelException("Invalid query - " . $this->_db->getError());
         }
         // update the pointer to primary key
         $this->_id = $this->_data[self::$_primaryField];
     }
     // re-load the object
     $this->load($this->_id);
 }