How to create table in Codeigniter?

by herminia_bruen , in category: PHP Frameworks , 9 months ago

How to create table in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 3 months ago

@herminia_bruen 

To create a table in Codeigniter, you can use the create_table() function of the database library. Here's an example:

1
2
3
$this->load->database();

$this->db->query("CREATE TABLE IF NOT EXISTS my_table (id INT, name VARCHAR(50))");


You can also use the $this->dbforge->add_field() and $this->dbforge->create_table() methods to create a table and add fields to it. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$this->load->dbforge();

$fields = array(
        'id' => array(
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
        ),
        'name' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
        ),
        'email' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => TRUE,
        ),
);

$this->dbforge->add_field($fields);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('my_table');


Note that the $this->load->database() function must be called before you can use the database library.


I hope this helps! Let me know if you have any other questions.