8.2.x database.inc db_insert($table, array $options = array())
8.0.x database.inc db_insert($table, array $options = array())
8.1.x database.inc db_insert($table, array $options = array())
7.x database.inc db_insert($table, array $options = array())

Returns a new InsertQuery object for the active database.

Parameters

$table: The table into which to insert.

$options: An array of options to control how the query operates.

Return value

InsertQuery A new InsertQuery object for this connection.

Related topics

150 calls to db_insert()
actions_synchronize in includes/actions.inc
Synchronizes actions that are provided by modules in hook_action_info().
aggregator_categorize_items_submit in modules/aggregator/aggregator.pages.inc
Form submission handler for aggregator_categorize_items().
aggregator_save_category in modules/aggregator/aggregator.module
Adds/edits/deletes aggregator categories.
aggregator_save_feed in modules/aggregator/aggregator.module
Add/edit/delete an aggregator feed.
aggregator_save_item in modules/aggregator/aggregator.processor.inc
Adds/edits/deletes an aggregator item.

... See full list

File

includes/database/database.inc, line 2482
Core systems for the database layer.

Code

function db_insert($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->insert($table, $options);
}

Comments

drclaw’s picture

Simple Example taken from http://drupal.org/node/310079 Check it out for more information!

// For the following query:
// INSERT INTO {node} (title, uid, created) VALUES ('Example', 1, 1221717405)

$nid = db_insert('node') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
  'created' => REQUEST_TIME,
))
->execute();

// Above Example is Equivalent to the Following in D6
$result = db_query("INSERT INTO {node} (title, uid, created) VALUES (%s, %d, %d)", 'Example', 1, time());

// OR using drupal_write_record... 
$data = array(
  'title' => 'Example',
  'uid' => 1,
  'created' => REQUEST_TIME,
);
drupal_write_record('node', $data);

sunly917’s picture

Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively. see https://api.drupal.org/api/drupal/includes%21database%21database.inc/fun...

danithaca’s picture

brazorf’s picture

Looking for $options documentation here http://drupal.org/node/1911206

ignaciogutierrez’s picture

If you have an auto increment field, you can use this code to get last id inserted:

db_insert($table)->fields($data)->execute();
$lastId = Database::getConnection()->lastInsertId();

Remember that Drupal Database Connections are PDO Connections, so you can use PDO::lastInsertId()

Ayesh’s picture

Return value of the db_insert function is the auto-increment field's value.
Ex:

$nid = db_insert('node') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
  'created' => REQUEST_TIME,
))
->execute();
dpm($nid); // Numeric NID of the just-created node. 
bpirkle’s picture

To be clear, the auto-increment field's value is returned by InsertQuery::execute, not by db_insert.

I'm not trying to be pedantic, I just wanted to avoid any confusion between Ayesh's comment and the db_insert return value as documented at the top of this page. The most common usage is exactly as Ayesh posted: chain an execute() call to the end of the statement and capture the auto-increment value returned from execute().

oxtor’s picture

I found this good example for multi insert.

    $values = array(
    array(
    'title' => 'Example',
    'uid' => 1,
    'created' => REQUEST_TIME,
    ),
    array(
    'title' => 'Example 2',
    'uid' => 1,
    'created' => REQUEST_TIME,
    ),
    array(
    'title' => 'Example 3',
    'uid' => 2,
    'created' => REQUEST_TIME,
    ),
    );
    $query = db_insert('node')->fields(array('title', 'uid', 'created'));
    foreach ($values as $record) {
    $query->values($record);
    }
    $query->execute();

I found it at this link, http://dropbucket.org/node/111
I thought it a good idea to post it because I found little documentation about

wuxiaogu’s picture

These code are good.But I think this last line should be put in the "foreach".

aBrookland’s picture

You only want to call execute() on the query once all values have been added in the foreach.

zonesny’s picture

Hope this saves someone a headache. In my case, I had inadvertently used a reserved word (release) for the database table name, which produced the above-referenced error via db_insert(). I had two options: a) change the table name, or b) surround the name in backticks `. I discovered that with option b, I actually needed to use BOTH backticks and quotes to avoid the error.

For example:

db_insert('`release`')
->fields(array('release_id', 'release_title', 'created', 'deleted'))
->values(array(
		'release_id' => 12345678,
		'release_title' => 'Up',
		'created' => REQUEST_TIME,
		'deleted' => 0
		))
->execute();
anujdeo’s picture

What will be the return value in case of any error or failure while inserting a record?

heylookalive’s picture

0 I believe!

JayDarnell’s picture

I'm testing this right now. My table doesn't have an auto incrementing field so this is simply returning 0 for every single row. Can anyone clarify what this should return if there is an error?

ElusiveMind’s picture

Do not use drupal_write_record for big int values. It will be dumbed down to 32bit instead of 64 and windows doesn't handle it gracefully. drupal_write_record should be deprecated.