Database Forge Class

The Database Forge Class contains methods that help you manage yourdatabase.

Initializing the Forge Class

Important

In order to initialize the Forge class, your databasedriver must already be running, since the forge class relies on it.

Load the Forge Class as follows:

  1. $forge = \Config\Database::forge();

You can also pass another database group name to the DB Forge loader, in casethe database you want to manage isn’t the default one:

  1. $this->myforge = \Config\Database::forge('other_db');

In the above example, we’re passing the name of a different database groupto connect to as the first parameter.

Creating and Dropping Databases

$forge->createDatabase(‘db_name’)

Permits you to create the database specified in the first parameter.Returns TRUE/FALSE based on success or failure:

  1. if ($forge->createDatabase('my_db'))
  2. {
  3. echo 'Database created!';
  4. }

An optional second parameter set to TRUE will add IF EXISTS statementor will check if a database exists before create it (depending on DBMS).

  1. $forge->createDatabase('my_db', TRUE);
  2. // gives CREATE DATABASE IF NOT EXISTS my_db
  3. // or will check if a database exists

$forge->dropDatabase(‘db_name’)

Permits you to drop the database specified in the first parameter.Returns TRUE/FALSE based on success or failure:

  1. if ($forge->dropDatabase('my_db'))
  2. {
  3. echo 'Database deleted!';
  4. }

Creating and Dropping Tables

There are several things you may wish to do when creating tables. Addfields, add keys to the table, alter columns. CodeIgniter provides amechanism for this.

Adding fields

Fields are normally created via an associative array. Within the array, you mustinclude a ‘type’ key that relates to the datatype of the field. Forexample, INT, VARCHAR, TEXT, etc. Many datatypes (for example VARCHAR)also require a ‘constraint’ key.

  1. $fields = [
  2. 'users' => [
  3. 'type' => 'VARCHAR',
  4. 'constraint' => 100,
  5. ],
  6. ];
  7. // will translate to "users VARCHAR(100)" when the field is added.

Additionally, the following key/values can be used:

  • unsigned/true : to generate “UNSIGNED” in the field definition.
  • default/value : to generate a default value in the field definition.
  • null/true : to generate “NULL” in the field definition. Without this,the field will default to “NOT NULL”.
  • auto_increment/true : generates an auto_increment flag on thefield. Note that the field type must be a type that supports this,such as integer.
  • unique/true : to generate a unique key for the field definition.
  1. $fields = [
  2. 'id' => [
  3. 'type' => 'INT',
  4. 'constraint' => 5,
  5. 'unsigned' => true,
  6. 'auto_increment' => true
  7. ],
  8. 'title' => [
  9. 'type' => 'VARCHAR',
  10. 'constraint' => '100',
  11. 'unique' => true,
  12. ],
  13. 'author' => [
  14. 'type' =>'VARCHAR',
  15. 'constraint' => 100,
  16. 'default' => 'King of Town',
  17. ],
  18. 'description' => [
  19. 'type' => 'TEXT',
  20. 'null' => true,
  21. ],
  22. 'status' => [
  23. 'type' => 'ENUM',
  24. 'constraint' => ['publish', 'pending', 'draft'],
  25. 'default' => 'pending',
  26. ],
  27. ];

After the fields have been defined, they can be added using$forge->addField($fields); followed by a call to thecreateTable() method.

$forge->addField()

The add fields method will accept the above array.

Passing strings as fields

If you know exactly how you want a field to be created, you can pass thestring into the field definitions with addField()

  1. $forge->addField("label varchar(100) NOT NULL DEFAULT 'default label'");

Note

Passing raw strings as fields cannot be followed by addKey() calls on those fields.

Note

Multiple calls to addField() are cumulative.

Creating an id field

There is a special exception for creating id fields. A field with typeid will automatically be assigned as an INT(9) auto_incrementingPrimary Key.

  1. $forge->addField('id');
  2. // gives id INT(9) NOT NULL AUTO_INCREMENT

Adding Keys

Generally speaking, you’ll want your table to have Keys. This isaccomplished with $forge->addKey(‘field’). The optional secondparameter set to TRUE will make it a primary key and the thirdparameter set to TRUE will make it a unique key. Note that addKey()must be followed by a call to createTable().

Multiple column non-primary keys must be sent as an array. Sample outputbelow is for MySQL.

  1. $forge->addKey('blog_id', TRUE);
  2. // gives PRIMARY KEY `blog_id` (`blog_id`)
  3.  
  4. $forge->addKey('blog_id', TRUE);
  5. $forge->addKey('site_id', TRUE);
  6. // gives PRIMARY KEY `blog_id_site_id` (`blog_id`, `site_id`)
  7.  
  8. $forge->addKey('blog_name');
  9. // gives KEY `blog_name` (`blog_name`)
  10.  
  11. $forge->addKey(['blog_name', 'blog_label']);
  12. // gives KEY `blog_name_blog_label` (`blog_name`, `blog_label`)
  13.  
  14. $forge->addKey(['blog_id', 'uri'], FALSE, TRUE);
  15. // gives UNIQUE KEY `blog_id_uri` (`blog_id`, `uri`)

To make code reading more objective it is also possible to add primaryand unique keys with specific methods:

  1. $forge->addPrimaryKey('blog_id');
  2. // gives PRIMARY KEY `blog_id` (`blog_id`)
  3.  
  4. $forge->addUniqueKey(['blog_id', 'uri']);
  5. // gives UNIQUE KEY `blog_id_uri` (`blog_id`, `uri`)

Adding Foreign Keys

Foreign Keys help to enforce relationships and actions across your tables. For tables that support Foreign Keys,you may add them directly in forge:

  1. $forge->addForeignKey('users_id','users','id');
  2. // gives CONSTRAINT `TABLENAME_users_foreign` FOREIGN KEY(`users_id`) REFERENCES `users`(`id`)

You can specify the desired action for the “on delete” and “on update” properties of the constraint:

  1. $forge->addForeignKey('users_id','users','id','CASCADE','CASCADE');
  2. // gives CONSTRAINT `TABLENAME_users_foreign` FOREIGN KEY(`users_id`) REFERENCES `users`(`id`) ON DELETE CASCADE ON UPDATE CASCADE

Creating a table

After fields and keys have been declared, you can create a new tablewith

  1. $forge->createTable('table_name');
  2. // gives CREATE TABLE table_name

An optional second parameter set to TRUE adds an “IF NOT EXISTS” clauseinto the definition

  1. $forge->createTable('table_name', TRUE);
  2. // gives CREATE TABLE IF NOT EXISTS table_name

You could also pass optional table attributes, such as MySQL’s ENGINE:

  1. $attributes = ['ENGINE' => 'InnoDB'];
  2. $forge->createTable('table_name', FALSE, $attributes);
  3. // produces: CREATE TABLE `table_name` (...) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci

Note

Unless you specify the CHARACTER SET and/or COLLATE attributes,createTable() will always add them with your configured charset_and _DBCollat values, as long as they are not empty (MySQL only).

Dropping a table

Execute a DROP TABLE statement and optionally add an IF EXISTS clause.

  1. // Produces: DROP TABLE table_name
  2. $forge->dropTable('table_name');
  3.  
  4. // Produces: DROP TABLE IF EXISTS table_name
  5. $forge->dropTable('table_name',TRUE);

Dropping a Foreign Key

Execute a DROP FOREIGN KEY.

  1. // Produces: ALTER TABLE 'tablename' DROP FOREIGN KEY 'users_foreign'
  2. $forge->dropForeignKey('tablename','users_foreign');

Renaming a table

Executes a TABLE rename

  1. $forge->renameTable('old_table_name', 'new_table_name');
  2. // gives ALTER TABLE old_table_name RENAME TO new_table_name

Modifying Tables

Adding a Column to a Table

$forge->addColumn()

The addColumn() method is used to modify an existing table. Itaccepts the same field array as above, and can be used for an unlimitednumber of additional fields.

  1. $fields = [
  2. 'preferences' => ['type' => 'TEXT']
  3. ];
  4. $forge->addColumn('table_name', $fields);
  5. // Executes: ALTER TABLE table_name ADD preferences TEXT

If you are using MySQL or CUBIRD, then you can take advantage of theirAFTER and FIRST clauses to position the new column.

Examples:

  1. // Will place the new column after the `another_field` column:
  2. $fields = [
  3. 'preferences' => ['type' => 'TEXT', 'after' => 'another_field']
  4. ];
  5.  
  6. // Will place the new column at the start of the table definition:
  7. $fields = [
  8. 'preferences' => ['type' => 'TEXT', 'first' => TRUE]
  9. ];

Dropping Columns From a Table

$forge->dropColumn()

Used to remove a column from a table.

  1. $forge->dropColumn('table_name', 'column_to_drop'); // to drop one single column

Used to remove multiple columns from a table.

  1. $forge->dropColumn('table_name', 'column_1,column_2'); // by proving comma separated column names
  2. $forge->dropColumn('table_name', ['column_1', 'column_2']); // by proving array of column names

Modifying a Column in a Table

$forge->modifyColumn()

The usage of this method is identical to addColumn(), except italters an existing column rather than adding a new one. In order tochange the name, you can add a “name” key into the field defining array.

  1. $fields = [
  2. 'old_name' => [
  3. 'name' => 'new_name',
  4. 'type' => 'TEXT',
  5. ],
  6. ];
  7. $forge->modifyColumn('table_name', $fields);
  8. // gives ALTER TABLE table_name CHANGE old_name new_name TEXT

Class Reference

  • CodeIgniter\Database\Forge
    • addColumn($table[, $field = []])

Parameters:

  1. - **$table** (_string_) Table name to add the column to
  2. - **$field** (_array_) Column definition(s)Returns:

TRUE on success, FALSE on failureReturn type:bool

Adds a column to a table. Usage: See Adding a Column to a Table.

  • addField($field)

Parameters:

  1. - **$field** (_array_) Field definition to addReturns:

CodeIgniterDatabaseForge instance (method chaining)Return type:CodeIgniterDatabaseForge

Adds a field to the set that will be used to create a table. Usage: See Adding fields.

  • addKey($key[, $primary = FALSE[, $unique = FALSE]])

Parameters:

  1. - **$key** (_mixed_) Name of a key field or an array of fields
  2. - **$primary** (_bool_) Set to TRUE if it should be a primary key or a regular one
  3. - **$unique** (_bool_) Set to TRUE if it should be a unique key or a regular oneReturns:

CodeIgniterDatabaseForge instance (method chaining)Return type:CodeIgniterDatabaseForge

Adds a key to the set that will be used to create a table. Usage: See Adding Keys.

  • addPrimaryKey($key)

Parameters:

  1. - **$key** (_mixed_) Name of a key field or an array of fieldsReturns:

CodeIgniterDatabaseForge instance (method chaining)Return type:CodeIgniterDatabaseForge

Adds a primary key to the set that will be used to create a table. Usage: See Adding Keys.

  • addUniqueKey($key)

Parameters:

  1. - **$key** (_mixed_) Name of a key field or an array of fieldsReturns:

CodeIgniterDatabaseForge instance (method chaining)Return type:CodeIgniterDatabaseForge

Adds a unique key to the set that will be used to create a table. Usage: See Adding Keys.

  • createDatabase($dbName[, $ifNotExists = FALSE])

Parameters:

  1. - **$db_name** (_string_) Name of the database to create
  2. - **$ifNotExists** (_string_) Set to TRUE to add an IF NOT EXISTS clause or check if database existsReturns:

TRUE on success, FALSE on failureReturn type:bool

Creates a new database. Usage: See Creating and Dropping Databases.

  • createTable($table[, $if_not_exists = FALSE[, array $attributes = []]])

Parameters:

  1. - **$table** (_string_) Name of the table to create
  2. - **$if_not_exists** (_string_) Set to TRUE to add an IF NOT EXISTS clause
  3. - **$attributes** (_string_) An associative array of table attributesReturns:

Query object on success, FALSE on failureReturn type:mixed

Creates a new table. Usage: See Creating a table.

  • dropColumn($table, $column_name)

Parameters:

  1. - **$table** (_string_) Table name
  2. - **$column_names** (_mixed_) Comma-delimited string or an array of column namesReturns:

TRUE on success, FALSE on failureReturn type:bool

Drops single or multiple columns from a table. Usage: See Dropping Columns From a Table.

  • dropDatabase($dbName)

Parameters:

  1. - **$dbName** (_string_) Name of the database to dropReturns:

TRUE on success, FALSE on failureReturn type:bool

Drops a database. Usage: See Creating and Dropping Databases.

  • dropTable($table_name[, $if_exists = FALSE])

Parameters:

  1. - **$table** (_string_) Name of the table to drop
  2. - **$if_exists** (_string_) Set to TRUE to add an IF EXISTS clauseReturns:

TRUE on success, FALSE on failureReturn type:bool

Drops a table. Usage: See Dropping a table.

  • modifyColumn($table, $field)

Parameters:

  1. - **$table** (_string_) Table name
  2. - **$field** (_array_) Column definition(s)Returns:

TRUE on success, FALSE on failureReturn type:bool

Modifies a table column. Usage: See Modifying a Column in a Table.

  • renameTable($table_name, $new_table_name)

Parameters:

  1. - **$table** (_string_) Current of the table
  2. - **$new_table_name** (_string_) New name of the tableReturns:

Query object on success, FALSE on failureReturn type:mixed

Renames a table. Usage: See Renaming a table.