php CodeIgniter - 如何捕捉数据库错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7843406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:29:08  来源:igfitidea点击:

CodeIgniter - how to catch DB errors?

phpcodeigniter

提问by StackOverflowNewbie

Is there a way to make CIthrow an exceptionwhen it encounters a DB errorinstead of displaying a message like:

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

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

发生数据库错误 错误编号:1054 'where 子句' 中的未知列 'foo' 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.

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

采纳答案by Oskenso Kashi

Try these CI functions

试试这些 CI 功能

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

UPDATE

更新

Functions are deprecated, use "error()" instead:

不推荐使用函数,请改用“error()”:

$this->db->error(); 

回答by RayJ

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

回答by CodeGodie

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

在 Codeigniter 3.0 (CI3) 中,您所要做的就是 $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

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

如果您需要获取发生的最后一个错误,则 error() 方法将返回一个包含其代码和消息的数组

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

回答by Kabir Hossain

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

您必须在 config/database.php -> 中关闭数据库的调试

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

It is better for your website security.

更有利于您的网站安全。

回答by tlogbon

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.

我知道这个线程很旧,但以防万一有人遇到这个问题。这是我在不涉及 CI db 类的情况下使用的技巧。保持调试并在错误视图文件中抛出异常。

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.phpreplace all content with the following:

然后在您的数据库错误视图文件中,我的application/errors/error_db.php将所有内容替换为以下内容:

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

由于视图文件将被调用,错误总是作为异常抛出,您可以稍后为不同的环境添加不同的视图。

回答by da1lbi3

I have created an simple library for that:

我为此创建了一个简单的库:

<?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
            )
        );
    }

}

The example query:

示例查询:

function insertId($id){
    $data = array(
        'id' => $id,
    );

    $this->db->insert('test', $data);
    $this->exceptions->checkForError();
    return $this->db->insert_id();
}

And I can catch it this way in my controller:

我可以在我的控制器中以这种方式捕获它:

 try {
     $this->insertThings->insertId("1");
 } catch (UserException $error){
     //do whatever you want when there is an mysql error

 }

回答by dlg_

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

最好的事物

回答by Adriano Gon?alves

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

将此代码放在 application/core 文件夹中名为 MY_Exceptions.php 的文件中:

<?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
{

}

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

它将使所有 Code Igniter 错误都被视为异常 (CiError)。然后,打开所有数据库调试:

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

回答by Kabir Hossain

Use it

用它

    $this->db->_error_message(); 

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

您将在配置文件夹的 database.php 中更改它

回答by the_martux

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']);

    if(!$res)
    {
        $error = $this->db->error();
        return $error;
        //return array $error['code'] & $error['message']
    }
    else
    {
        return 1;
    }