How to recover from failed database query in CodeIgniter?
codeigniter, database, error-handling, mysql, php
Solution
One of the ways to achieve this is
First.
Set ['db_debug'] = FALSE; in config/database.php
Then,
In your model -
public function attempt_one($data) {
//build your query ....
$query_result = $this->db->insert('table_name');
if(!$query_result) {
$this->error = $this->db->_error_message();
$this->errorno = $this->db->_error_number();
return false;
}
return $something;
}
public function attempt_two() {
//another query goes in here ...
}
in your controller -
public function someAction ()
{
//some code
$data = $some_data;
$result1 = $this->yourmodel->attempt_one($data);
if($result1 === false)
{
//Some code to send an email alert that first query failed with error message
//and/or log the error message/ number
$result2 = $this->yourmodel->attempt_two($data);
}
}
Problem
In CodeIgniter, if your sql query fails, then the script stops running and you get an error. Is there any way to do it so you can try a query, and if it fails, then you silently detect it and try a different query without the user knowing that the query failed?