function dbtng_example_entry_insert in Examples for Developers 7
Save an entry in the database.
The underlying DBTNG function is db_insert().
In Drupal 6, this would have been:
db_query("INSERT INTO {dbtng_example} (name, surname, age)\n VALUES ('%s', '%s', '%d')", $entry['name'], $entry['surname'], $entry['age']);
Exception handling is shown in this example. It could be simplified without the try/catch blocks, but since an insert will throw an exception and terminate your application if the exception is not handled, it is best to employ try/catch.
Parameters
array $entry: An array containing all the fields of the database record.
See also
Related topics
2 calls to dbtng_example_entry_insert()
- DBTNGExampleUnitTestCase::testAPIExamples in dbtng_example/
dbtng_example.test - Test several combinations, adding entries, updating and deleting.
- dbtng_example_form_add_submit in dbtng_example/
dbtng_example.module - Submit handler for 'add entry' form.
File
- dbtng_example/
dbtng_example.module, line 96 - This is an example outlining how a module can make use of the new DBTNG database API in Drupal 7.
Code
function dbtng_example_entry_insert($entry) {
$return_value = NULL;
try {
$return_value = db_insert('dbtng_example')
->fields($entry)
->execute();
} catch (Exception $e) {
drupal_set_message(t('db_insert failed. Message = %message, query= %query', array(
'%message' => $e
->getMessage(),
'%query' => $e->query_string,
)), 'error');
}
return $return_value;
}