Example #1
0
 /**
  * Add new record
  *
  *  <code>
  *      $users->insert(array('login'=>'admin', 'password'=>'pass'));
  *  </code>
  *
  * @param  array   $fields Record fields to insert
  * @return boolean
  */
 public function insert(array $fields = null)
 {
     // Set save flag to true
     $save = true;
     // Foreach fields check is current field alredy exists
     if (count($fields) !== 0) {
         foreach ($fields as $key => $value) {
             if (Table::_selectOne($this->table, "fields/{$key}") == null) {
                 $save = false;
                 break;
             }
         }
     }
     // Get table fields and create fields names array
     $_fields = Table::_selectOne($this->table, "fields");
     foreach ($_fields as $key => $value) {
         $field_names[(string) $key] = (string) $key;
     }
     // Save record
     if ($save) {
         // Find autoincrement option
         $inc = Table::_selectOne($this->table, "options/autoincrement");
         // Increment
         $inc_upd = $inc + 1;
         // Add record
         $node = $this->table['xml_object']->addChild(XML::safe($this->name));
         // Update autoincrement
         Table::_updateWhere($this->table, "options", array('autoincrement' => $inc_upd));
         // Add common record fields: id and uid
         $node->addChild('id', $inc_upd);
         $node->addChild('uid', Table::_generateUID());
         // If exists fields to insert then insert them
         if (count($fields) !== 0) {
             $table_fields = array_diff_key($field_names, $fields);
             // Defined fields
             foreach ($table_fields as $table_field) {
                 $node->addChild($table_field, '');
             }
             // User fields
             foreach ($fields as $key => $value) {
                 $node->addChild($key, XML::safe($value));
             }
         }
         // Save table
         return Table::_save($this->table);
     } else {
         return false;
     }
 }