I want to create migration for updating table. So I want to check if columns exist or not in db table before executing to remove error of duplicate column. Is there any to check using db forge in CodeIgniter? Thank you for help.
Check if multiple column exist in table using CodeIgniter database forge
270 Views Asked by Bijay Shrestha At
2
There are 2 best solutions below
0
On
To check the presence of several columns in a table with CodeIgniter Database Forge, use the below code:
$this->load->dbforge();
$table_name = 'your_table_name';
$columns = array('column1', 'column2', 'column3');
$table_fields = $this->db->list_fields($table_name);
$missing_columns = array_diff($columns, $table_fields);
if (!empty($missing_columns)) {
echo ""The following columns are missing: "" . implode(', ', $missing_columns);
} else {
echo ""All columns exist in the table."";
}
Note the following prerequisites:
• Download the dbforge library with the help of the $this→load→dbforge() function.
• Specify the name of the table you want to check for the presence of columns using $table_name
• Create the data set for the column names you want to check using $columns
• fetch the data set of all table fields using $table_fields = $this→db→list_fields($table_name);
• Apply array_diff() to compare the $columns data set to the $table_fields data set. This way you can check the missing columns
If the columns are missing, the output message will define which exactly columns are absent. If all columns are present in the table, the output message will state all columns existing.
ALTER TABLE table_name DROP COLUMN IF EXISTS col1, COLUMN IF EXISTS col2; dbforge used in Codeigniter to add or modify the tables.
$this->dbforge->add_column('table_name', $fields);$this->dbforge->drop_column('table_name','column_name');