0

I have a module and an installation file that is used to create a table.

According to my requirement, I need to add an another table in the same install file. I know that by using hook_schema() we can create n number of tables.
But we need to uninstall and reinstall again to create the tables. If I use this, my existing data will be lost, so I am not supposed to do this.

Is there any way to create a table without uninstalling and reinstalling the module?

2
  • Can you specify which version of Drupal we're using ?
    – yvan
    Oct 27 '11 at 10:48
  • I am using Drupal 6
    – Fero
    Oct 27 '11 at 10:49
4

This link answered my question: Updating tables: hook_update_N() functions.

For example:

In Drupal 7:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}
?>

and in Drupal 6:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_6101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  $ret = array();
  db_create_table($ret, 'mytable2', $schema['mytable2']);
  return $ret;
}
?>
1
  • Don't forget to also add the new table schema in your hook_shema, otherwise for the new install you'll not have the added table.
    – yvan
    Oct 27 '11 at 10:51
0

hook_install() is called only when the module is first installed; after that, hook_install() will be called only if you first uninstall the module.

When you are updating a module, you need to implement hook_update_N(), which runs all times the module is updated. At the same time, the implementation of hook_schema() needs to be updated to include all the schema used from the module, for who installs the module for the first time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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