How to change and update database using hook_update_N in Drupal 8

  1. Create *.install file inside your module folder. If your module is named mymodule, the path of the *.install file should be in "/module/mymodule/mymodule.install".
  2. Impletment the hook_update_N function on the mymodule.install file. The character N is the version number of the update.
    • In Drupal 8, The first digital should be 8.
    • The second digital is the api version of the module.
    • The last two digitals is the serial number of the update.
    • The number of N value will be automatically stored in the database after each successful update. It will be ignored If N value is less or equal than the number that stored in the database.
    • You may use function drupal_get_installed_schema_version('module_name') to get the N value that stored in the database. If you have never use hook_update_N to update your module before. The number of N value should be set to 8001.
      //Append following function into mymodule.install
      function mymodule_update_8001(){
         //Column newField will be added into the mytable
         $spec = array(
          'type' => 'varchar',
          'description' => "newField",
          'length' => 255,
          'not null' => FALSE,
        db_add_field('mytable', 'newField', $spec);
  3. Set the value of $settings['update_free_access']  to true on /sites/default/settings.php
  4. Goto the update.php. Entry the link http:// yourdomain /update.php through your browser.
    • After entered into update.php, press the continue button and go to the next step. 
    • You should found the newest number of the update version.
    • If can't found the version number and it shows "No pending updates".
      • Please check whether the N value is correct.
      • Otherwise, please noted that your module name cannot contains any capital letter.
  5. Finally, follow the instructions and complete the update process.