0

Is there a method to be called that will get the ID of the record just inserted?

In my module the first thing done is the insert of some data into a table.

After that I have other things to do in the same submit method of my module that needs the ID of the record that was created, so I can place it into tables that are related.

I've tried

`$reminder_query->execute();

$reminder_id = $reminder_query->id();`

But keep getting an error.

Error: Call to undefined method Drupal\mysql\Driver\Database\mysql\Insert::id() in Drupal\rmdrs\Form\ReminderForm->submitForm()

1
  • you can use $query->range(0, 1);, it would help in your case.
    – Barry
    Dec 4, 2023 at 23:26

2 Answers 2

0
$db = \Drupal::database();

$reminder_query = $db->insert('rmdrs_reminders');
$reminder_query->fields ([
  .......
]);

$reminder_query->values([
  .......
]);
$reminder_query->execute();
$reminder_id = $db->lastInsertId(); // Must refer to the connection to get ID immediately after it is inserted
0
// Assuming $reminder_query is a database query object.
$reminder_query = \Drupal::database()->select('your_table_name', 't')
  ->fields('t')
  ->condition('your_condition_field', $your_condition_value);

// Add the range to limit the result set to one row.
$reminder_query->range(0, 1);

// Execute the query and fetch the result.
$result = $reminder_query->execute()->fetch();

// Check if a result was found.
if ($result) {
  // Access the 'id' field from the result.
  $reminder_id = $result->id;
  // Use $reminder_id as needed.
} else {
  // Handle the case where no result was found.
}

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.