· 8 years ago · May 21, 2018, 04:54 PM
1public function create_table($name, $if_not_exists = FALSE, $charset = "UTF8")
2 {
3 if( empty($this->cols) )
4 {
5 show_error('You must first add columns and keys before creating a table', FALSE, E_ERROR);
6 return FALSE;
7 }
8
9 // NOW, we can continue with creating the table
10 $sql = 'CREATE TABLE ';
11
12 // Add IF NOT EXISTS if set to true
13 if($if_not_exists == TRUE)
14 {
15 $sql .= 'IF NOT EXISTS ';
16 }
17
18 // Add the table name
19 $sql .= "`$name` (". PHP_EOL;
20
21 // Loop through and add each column to the sql
22 foreach($this->cols as $name => $col)
23 {
24 if($col['type'] != 'text')
25 {
26 $sql .= "`$name` ". $col['type'] ."(". $col['size'] .")";
27 }
28 else
29 {
30 $sql .= "`$name` text";
31 }
32
33 // Set allow Null
34 if($col['allow_null'] == FALSE || $col['auto_increment'] == TRUE)
35 {
36 $sql .= " NOT NULL";
37 }
38
39 // Set auto increment
40 if($col['auto_increment'] == TRUE)
41 {
42 $sql .= " AUTO_INCREMENT";
43 }
44
45 // Add default
46 else
47 {
48 ($col['default'] === NULL) ? $d = 'NULL' : $d = "'". $col['default'] ."'";
49 $sql .= " DEFAULT ". $d;
50 }
51
52 // Add comment if one exists
53 if($col['comment'] != NULL)
54 {
55 $sql .= " COMMENT '". $col['comment'] ."'";
56 }
57
58 // Add ending
59 $sql .= ",". PHP_EOL;
60 }
61
62 // Add primary keys
63 if(!empty($this->keys))
64 {
65 $sql .= "PRIMARY KEY (";
66 foreach($this->keys as $key)
67 {
68 $sql .= "`$key`";
69 }
70 $sql .= ")". PHP_EOL;
71 }
72
73 // Finish
74 $sql .= ") DEFAULT CHARSET=". $charset .";";
75 }