I am storing some data into the database

try {
      $fields = array(
        'uid' => \Drupal::currentUser()->id(),
        'value' => $form_state->getValue('blood_sugar'),
        'created' => time(),

Later on I would like to check the latest inserted row to check if it was inserted within the last hour.

Could someone provide an example of fetching one item from the database?

1 Answer 1


You can follow the Database Abstraction API documentation. Although most of that documentation points to using the deprecated methods. You may find the current classes and methods, by clicking into each function that you need (such as db_select), and reading the deprecated messages.

This is very similar to what you have done for inserts (using Dynamic Query).

$id = Database::getConnection()->select('blood_sugar_monitor')
  ->fields('blood_sugar_monitor', ['my_primary_key'])
  ->range(0, 1)
  ->orderBy('my_primary_key', 'DESC')
  • db_select('blood_sugar_monitor', 'bsm')->fields('bsm', ['some_field'])->orderBy('bsm.some_key', 'DESC')->range(0, 1)->execute()->fetchField()
    – user21641
    Commented Mar 9, 2016 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.