The best way to add a column to an existing table in drupal

English
  1. /*
  2.  * Implements hook_schema_alter().
  3.  */
  4. function mymodule_schema_alter(&$schema) {
  5. $schema['tablename']['fields']['fieldname'] = array(
  6. 'type' => 'varchar',
  7. 'default' => null
  8. );
  9. }
  10.  
  11. /*
  12.  * Implements hook_install().
  13.  */
  14. function mymodule_install() {
  15. if (!db_field_exists('tablename', 'fieldname')) {
  16. $schema = drupal_get_schema('tablename');
  17. db_add_field('tablename', 'fieldname', $schema['fields']['fieldname']);
  18. }
  19. }
  20.  
  21. /*
  22.  * Implements hook_uninstall().
  23.  */
  24. function mymodule_uninstall() {
  25. if (db_field_exists('tablename', 'fieldname')) {
  26. db_drop_field('tablename', 'fieldname');
  27. }
  28. }
The code has been tested and works
Мультитег: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Target Image