To ensure the uniqueness of multiple fields like label and table-id in a MySQL database using CodeIgniter, you have a few reliable options:
Option 1: Add a Unique Composite Index in the Database
You can enforce uniqueness at the database level by creating a composite unique key:
ALTER TABLE context ADD UNIQUE KEY unique_label_table (label, table_id);
This ensures that the combination of label and table_id is unique — so duplicate inserts will automatically fail.
Option 2: Check Before Insert in CodeIgniter
If you want to handle it in CodeIgniter before inserting, you can do:
$exists = $this->db->get_where('context', [
'label' => $item['label'],
'table_id' => $node['id']
])->row();
if (!$exists) {
$this->db->insert('context', [
'type_flow' => $node['name'],
'title' => $node['data']['title'],
'label' => $item['label'],
'type' => $item['type'],
'value' => $item['value'],
'table_id' => $node['id'],
]);
}
This checks whether a record with the same label and table_id already exists before inserting.
(Best Practice)
For data integrity, it's best to combine both:
Add a unique index in MySQL to prevent duplicates.
Add a CodeIgniter check to avoid insert errors.