drupal_write_record

Versions
6
drupal_write_record($table, &$object, $update = array())
7
drupal_write_record($table, &$object, $primary_keys = array())

Save a record to the database based upon the schema.

Default values are filled in for missing items, and 'serial' (auto increment) types are filled in with IDs.

Parameters

$table The name of the table; this must exist in schema API.

$object The object to write. This is a reference, as defaults according to the schema may be filled in on the object, as well as ID on the serial type(s). Both array an object types may be passed.

$primary_keys If this is an update, specify the primary keys' field names. It is the caller's responsibility to know if a record for this object already exists in the database. If there is only 1 key, you may pass a simple string.

Return value

Failure to write a record will return FALSE. Otherwise SAVED_NEW or SAVED_UPDATED is returned depending on the operation performed. The $object parameter contains values for any serial fields defined by the $table. For example, $object->nid will be populated after inserting a new node.

Related topics

▾ 24 functions call drupal_write_record()

block_theme_initialize in modules/block/block.module
Assign an initial, default set of blocks for a theme.
contact_category_edit_form_submit in modules/contact/contact.admin.inc
Process the contact category edit page form submission.
field_create_field in modules/field/field.crud.inc
Create a field.
field_test_entity_save in modules/field/tests/field_test.entity.inc
Saves a test_entity.
file_save in includes/file.inc
Save a file object to the database.
filter_format_save in modules/filter/filter.module
Save a text format object to the database.
hook_menu_link_insert in modules/menu/menu.api.php
Inform modules that a menu link has been created.
image_effect_save in modules/image/image.module
Save an image effect.
image_style_save in modules/image/image.module
Save an image style.
locale_date_format_save in includes/locale.inc
Save locale specific date formats to the database.
node_save in modules/node/node.module
Save changes to a node or add a new node.
path_save in includes/path.inc
Save a path alias to the database.
scaffolding_example_record_save in developer/examples/scaffolding_example/scaffolding_example.module
Inserts a new record, or updates an existing one.
shortcut_set_save in modules/shortcut/shortcut.module
Saves a shortcut set.
system_date_format_save in modules/system/system.module
Save a date format to the database.
system_date_format_type_save in modules/system/system.module
Save a date type to the database.
taxonomy_term_save in modules/taxonomy/taxonomy.module
Save a term object to the database.
taxonomy_vocabulary_save in modules/taxonomy/taxonomy.module
Save a vocabulary given a vocabulary object.
upload_update_7000 in modules/upload/upload.install
Migrate upload module files from {files} to {file}.
user_role_save in modules/user/user.module
Save a user role to the database.
user_save in modules/user/user.module
Save changes to a user account or add a new user.
_block_rehash in modules/block/block.module
Update the 'block' DB table with the blocks currently exported by modules.
_field_write_instance in modules/field/field.crud.inc
Store an instance record in the field configuration database.
_node_save_revision in modules/node/node.module
Helper function to save a revision with the uid of the current user.

Code

includes/common.inc, line 5731

<?php
function drupal_write_record($table, &$object, $primary_keys = array()) {
  // Standardize $primary_keys to an array.
  if (is_string($primary_keys)) {
    $primary_keys = array($primary_keys);
  }

  $schema = drupal_get_schema($table);
  if (empty($schema)) {
    return FALSE;
  }

  // Convert to an object if needed.
  if (is_array($object)) {
    $object = (object) $object;
    $array = TRUE;
  }
  else {
    $array = FALSE;
  }

  $fields = array();

  // Go through our schema, build SQL, and when inserting, fill in defaults for
  // fields that are not set.
  foreach ($schema['fields'] as $field => $info) {
    // Special case -- skip serial types if we are updating.
    if ($info['type'] == 'serial' && !empty($primary_keys)) {
      continue;
    }

    // For inserts, populate defaults from schema if not already provided.
    if (!isset($object->$field) && empty($primary_keys) && isset($info['default'])) {
      $object->$field = $info['default'];
    }

    // Track serial field so we can helpfully populate them after the query.
    // NOTE: Each table should come with one serial field only.
    if ($info['type'] == 'serial') {
      $serial = $field;
    }

    // Build arrays for the fields and values in our query.
    if (isset($object->$field)) {
      if (empty($info['serialize'])) {
        $fields[$field] = $object->$field;
      }
      elseif (!empty($object->$field)) {
        $fields[$field] = serialize($object->$field);
      }
      else {
        $fields[$field] = '';
      }
    }

    // We don't need to care about type casting if value does not exist.
    if (!isset($fields[$field])) {
      continue;
    }

    // Special case -- skip null value if field allows null.
    if ($fields[$field] == NULL && $info['not null'] == FALSE) {
      continue;
    }

    // Type cast if field does not allow null. Required by DB API.
    if ($info['type'] == 'int' || $info['type'] == 'serial') {
      $fields[$field] = (int) $fields[$field];
    }
    elseif ($info['type'] == 'float') {
      $fields[$field] = (float) $fields[$field];
    }
    else {
      $fields[$field] = (string) $fields[$field];
    }
  }

  if (empty($fields)) {
    // No changes requested.
    // If we began with an array, convert back so we don't surprise the caller.
    if ($array) {
      $object = (array) $object;
    }
    return;
  }

  // Build the SQL.
  if (empty($primary_keys)) {
    $options = array('return' => Database::RETURN_INSERT_ID);
    if (isset($serial) && isset($fields[$serial])) {
      // If the serial column has been explicitly set with an ID, then we don't
      // require the database to return the last insert id.
      if ($fields[$serial]) {
        $options['return'] = Database::RETURN_AFFECTED;
      }
      // If a serial column does exist with no value (i.e. 0) then remove it as
      // the database will insert the correct value for us.
      else {
        unset($fields[$serial]);
      }
    }
    $query = db_insert($table, $options)->fields($fields);
    $return = SAVED_NEW;
  }
  else {
    $query = db_update($table)->fields($fields);
    foreach ($primary_keys as $key) {
      $query->condition($key, $object->$key);
    }
    $return = SAVED_UPDATED;
  }

  // Execute the SQL.
  if ($last_insert_id = $query->execute()) {
    if (isset($serial)) {
      // If the database was not told to return the last insert id, it will be
      // because we already know it.
      if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
        $object->$serial = $fields[$serial];
      }
      else {
        $object->$serial = $last_insert_id;
      }
    }
  }
  // If we have a single-field primary key but got no insert ID, the
  // query failed.
  elseif (count($primary_keys) == 1) {
    $return = FALSE;
  }

  // If we began with an array, convert back so we don't surprise the caller.
  if ($array) {
    $object = (array) $object;
  }

  return $return;
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.