[Drupal] How to add multiple columns to the existing custom table in Drupal

| | 1 min read

In Drupal, usage of custom modules to increase varied functionality and the use of the custom tables to store persistent data always encouraged. We can easily find the solutions by the vast entity of hooks provided by Drupal. In the case to add table structures, we use hook_schema were the structure of table stored in array.

In the custom feature to get the persistent data, ie., We will have to get the data stored in the custom table to add to the new table structure. Here, option is hook, hook_update_N.

We have a custom table with fields uid, nid, name and you need to add two more columns field1 and field2 to the same structure fetching all the table column data. Add new fields to the custom hook_update_N:

db_add_field($table, $field, $spec);

In the above code,

  • $table - custom table to which the new field to add.
  • $field - new field name
  • $spec- array of the field properties

If you have to add multiple fields to the structure ,then add the above code again with the arguments. Please note to add the new fields array in the hook_schema() function too. After updating the code please do run the file update.php to check the site for the new pending updates to configure.

Reference: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_add_field/7.