Example: Database (DBTNG)

  1. drupal
    1. 8
    2. 7

Database examples, including DBTNG.

'DBTNG' means 'Database: The Next Generation.' Yes, Drupallers are nerds.

General documentation is available at database abstraction layer documentation and at Database API.

The several examples here demonstrate basic database usage.

In Drupal 6, the recommended method to save or update an entry in the database was drupal_write_record() or db_query().

In Drupal 7 and forward, the usage of db_query() for INSERT, UPDATE, or DELETE is deprecated, because it is database-dependent. Instead specific functions are provided to perform these operations: db_insert(), db_update(), and db_delete() do the job now. (Note that drupal_write_record() is also deprecated.)

db_insert() example:

<?php
  // INSERT INTO {dbtng_example} (name, surname) VALUES('John, 'Doe')
  db_insert('dbtng_example')
    ->fields(array('name' => 'John', 'surname' => 'Doe'))
    ->execute();
?>

db_update() example:

<?php
  // UPDATE {dbtng_example} SET name = 'Jane' WHERE name = 'John'
  db_update('dbtng_example')
    ->fields(array('name' => 'Jane'))
    ->condition('name', 'John')
    ->execute();
?>

db_delete() example:

<?php
  // DELETE FROM {dbtng_example} WHERE name = 'Jane'
  db_delete('dbtng_example')
    ->condition('name', 'Jane')
    ->execute();
?>

See Database Abstraction Layer

See also

db_insert()

db_update()

db_delete()

drupal_write_record()

Functions & methods

NameDescription
dbtng_example_advanced_listRender a filtered list of entries in the database.
dbtng_example_entry_deleteDelete an entry from the database.
dbtng_example_entry_insertSave an entry in the database.
dbtng_example_entry_loadRead from the database using a filter array.
dbtng_example_entry_updateUpdate an entry in the database.
dbtng_example_form_addPrepare a simple form to add an entry, with all the interesting fields.
dbtng_example_form_add_submitSubmit handler for 'add entry' form.
dbtng_example_form_updateSample UI to update a record.
dbtng_example_form_update_callbackAJAX callback handler for the pid select.
dbtng_example_form_update_submitSubmit handler for 'update entry' form.
dbtng_example_helpImplements hook_help().
dbtng_example_installImplements hook_install().
dbtng_example_listRender a list of entries in the database.
dbtng_example_menuImplements hook_menu().
dbtng_example_schemaImplements hook_schema().
dbtng_example_uninstallImplements hook_uninstall().

examples/dbtng_example/dbtng_example.module, line 14