CodeIgniter - how to catch database errors?

Is there a way to get CI to throw an exception when it encounters a DB error instead of displaying such a message:

Database error occured Error number: 1054 Unknown column 'foo' in 'where clause' SELECT * FROM ( FooBar ) WHERE foo = '1'

NOTE. I want this to happen on only one controller. In other controllers, I am happy to display database error messages.

+55
php codeigniter
Oct 20 '11 at 23:22
source share
11 answers

Try these CI features

 $this->db->_error_message(); (mysql_error equivalent) $this->db->_error_number(); (mysql_errno equivalent) 
+54
Oct 21 '11 at 4:17
source share

Perhaps it:

 $db_debug = $this->db->db_debug; //save setting $this->db->db_debug = FALSE; //disable debugging for queries $result = $this->db->query($sql); //run query //check for errors, etc $this->db->db_debug = $db_debug; //restore setting 
+32
Jun 18 '13 at 6:15
source share

In Codeigniter 3.0 (CI3), all you have to do is $this->db->error()

If you need the last error that occurred, the error () method will return an array containing its code and message

http://www.codeigniter.com/user_guide/database/queries.html#handling-errors

+25
Jun 12 '15 at 18:38
source share

You must disable debugging for the database in config / database.php ->

 $db['default']['db_debug'] = FALSE; 

This is better for the security of your site.

+15
Jan 12 '14 at 10:43
source share

I know this thread is outdated, but just in case anyone else has this problem. This is the trick I used without touching the CI db classes. Leave your debug file and in your error viewer, highlight the exception.

So, you have db config, you have:

 $db['default']['db_debug'] = true; 

Then in your db error presentation file mine is in application/errors/error_db.php , replace all the contents as follows:

 <?php $message = preg_replace('/(<\/?p>)+/', ' ', $message); throw new Exception("Database error occured with message : {$message}"); ?> 

Since the view file will be called, the error will always be selected as an exception, later you can add different views for different environments.

+11
Dec 19 '14 at 12:47
source share

I created a simple library for this:

 <?php defined('BASEPATH') OR exit('No direct script access allowed'); class exceptions { public function checkForError() { get_instance()->load->database(); $error = get_instance()->db->error(); if ($error['code']) throw new MySQLException($error); } } abstract class UserException extends Exception { public abstract function getUserMessage(); } class MySQLException extends UserException { private $errorNumber; private $errorMessage; public function __construct(array $error) { $this->errorNumber = "Error Code(" . $error['code'] . ")"; $this->errorMessage = $error['message']; } public function getUserMessage() { return array( "error" => array ( "code" => $this->errorNumber, "message" => $this->errorMessage ) ); } } 

Request example:

 function insertId($id){ $data = array( 'id' => $id, ); $this->db->insert('test', $data); $this->exceptions->checkForError(); return $this->db->insert_id(); } 

And I can catch this in my controller:

  try { $this->insertThings->insertId("1"); } catch (UserException $error){ //do whatever you want when there is an mysql error } 
+4
Dec 27 '16 at 18:23
source share

Use it

  $this->db->_error_message(); 

Better to find a mistake. After the completion of your site. Close error messages using it

  $db['default']['db_debug'] = FALSE; 

You will change it in your config.php folder

+2
Jan 26 '14 at 11:24
source share

Put this code in the MY_Exceptions.php file in the application / core folder:

 <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * Class dealing with errors as exceptions */ class MY_Exceptions extends CI_Exceptions { /** * Force exception throwing on erros */ public function show_error($heading, $message, $template = 'error_general', $status_code = 500) { set_status_header($status_code); $message = implode(" / ", (!is_array($message)) ? array($message) : $message); throw new CiError($message); } } /** * Captured error from Code Igniter */ class CiError extends Exception { } 

This will cause all upstream errors to be treated as an exception (CiError). Then enable all database debugging:

 $db['default']['db_debug'] = true; 
+2
Jan 29 '16 at
source share

If one uses PDO, in addition to all the answers above.

I log my errors silently as shown below

  $q = $this->db->conn_id->prepare($query); if($q instanceof PDOStatement) { // go on with bind values and execute } else { $dbError = $this->db->error(); $this->Logger_model->logError('Db Error', date('Ymd H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' - '.'Message: '.$dbError['message']); } 
0
Mar 25 '18 at 1:56
source share

Disable error debugging.

  $data_user = $this->getDataUser(); $id_user = $this->getId_user(); $this->db->db_debug = false; $this->db->where(['id' => $id_user]); $res = $this->db->update(self::$table, $data_user['user']); if(!$res) { $error = $this->db->error(); return $error; //return array $error['code'] & $error['message'] } else { return 1; } 
0
Sep 25 '18 at 11:26
source share

an example that worked for me:

 $query = "some buggy sql statement"; $this->db->db_debug = false; if(!@$this->db->query($query)) { $error = $this->db->error(); // do something in error case }else{ // do something in success case } ... 

Best

0
Feb 04 '19 at 15:40
source share



All Articles