Codeigniter foreign key constraint check
codeigniter, constraints
Solution
in config folder database.php file find the line
$db['default']['db_debug']
and set it to FALSE. This will prevent Codeigniter from printing the error on the screen.
Also in the delete function you can check:
if ($this->db->_error_number() == 1451)
If you need to do something special when this happens.
Problem
Let me first explain the table structure: ``` +-----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | firstname | varchar(255) | NO | | NULL | | | name | varchar(255) | NO | | NULL | | +-----------+--------------+------+-----+---------+----------------+ ``` The id field is referenced from another table through a foreign key. Say I have a function in my model like this: ``` public function delete_user($id) { return $this->db->delete('users', array('id' => $id)); } ``` When this user is referenced from the other table, it should throw an error. The "bad" thing is, that Codeigniter actually shows that error on a full page: ``` Error Number: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`testing`.`users_link`, CONSTRAINT `users_link_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) DELETE FROM `users` WHERE `id` = '1' ``` Is there a way to make the delete_user function return FALSE instead of showing the error? I'd like to notify the user that they have to do something else first. I tried using transactions and returning the transaction_status, but that still throws the error.