2011-10-20 23:22
浏览 359

CodeIgniter - 如何捕获数据库错误?

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

A Database Error Occurred Error Number: 1054 Unknown column 'foo' in 'where clause' SELECT * FROM (FooBar) WHERE foo = '1'

NOTE: I only want this to happen in one controller. In the other controllers, I'm happy for it to display the DB error messages.

图片转代码服务由CSDN问答提供 功能建议

有没有办法让 CI 抛出异常 当遇到 DB错误而不是显示如下消息时:

发生数据库错误错误号:1054 未知列'foo 'in'where子句'SELECT * FROM( FooBar )WHERE foo ='1'

注意 :我只想在一个控制器中发生这种情况。 在其他控制器中,我很高兴它显示 DB错误消息

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

11条回答 默认 最新

  • douzi3756 2011-10-21 04:17

    Try these CI functions

    $this->db->_error_message(); (mysql_error equivalent)
    $this->db->_error_number(); (mysql_errno equivalent)
    打赏 评论
  • doujia6503 2013-06-18 06:15

    Maybe this:

    $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
    打赏 评论
  • doujingxi3356 2014-01-12 10:43

    You must turn debug off for database in config/database.php ->

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

    It is better for your website security.

    打赏 评论
  • drra6593 2014-01-26 11:24

    Use it


    It is better for finding error.After completing your site. Close the error messages using it

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

    You will change it in your config folder's database.php

    打赏 评论
  • dougu5886 2014-12-19 12:47

    I know this thread is old, but just in case there's someone else having this issue. This is a trick I used without touching the CI db classes. Leave your debug on and in your error view file, throw an exception.

    So in you db config, you have :

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

    Then in your db error view file, mine is in application/errors/error_db.php replace all content with the following:

    $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 get thrown as an exception, you may later add different views for different environment.

    打赏 评论
  • dongzhuang6417 2015-06-12 18:38

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

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


    打赏 评论
  • douguomou5094 2016-01-29 14:07

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

    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)
            $message = implode(" / ", (!is_array($message)) ? array($message) : $message);
            throw new CiError($message);
     * Captured error from Code Igniter
    class CiError extends Exception

    It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

    $db['default']['db_debug'] = true;
    打赏 评论
  • douxuanma4357 2016-12-27 18:23

    I have created an simple library for that:

    defined('BASEPATH') OR exit('No direct script access allowed');
    class exceptions {
        public function checkForError() {
            $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

    The example query:

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

    And I can catch it this way in my controller:

     try {
     } catch (UserException $error){
         //do whatever you want when there is an mysql error
    打赏 评论
  • dongshao6591 2018-03-25 01:56

    If one uses PDO, additional to all the answers above.

    I log my errors silently as 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('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);
    打赏 评论
  • douchao1879 2018-09-25 11:26

    Disable debugging of errors.

        $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']);
            $error = $this->db->error();
            return $error;
            //return array $error['code'] & $error['message']
            return 1;
    打赏 评论
  • duanhu7400 2019-02-04 15:40

    an example that worked for me:

    $query = "some buggy sql statement";
    $this->db->db_debug = false;
        $error = $this->db->error();
        // do something in error case
        // do something in success case


    打赏 评论

相关推荐 更多相似问题