如何从CodeIgniter中的失败数据库查询中恢复?

Cli*_*ote 4 php mysql database error-handling codeigniter

在CodeIgniter中,如果您的sql查询失败,那么脚本将停止运行并出现错误.有没有办法做到这一点,所以你可以尝试查询,如果它失败,那么你静静地检测它并尝试不同的查询,而用户不知道查询失败?

Wes*_*rch 5

您可以将Exceptions类修改为...抛出异常.只要创建MY_Exceptions.phpapplication/core/:

class MY_Exceptions extends CI_Exceptions {

    function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        // BEGIN EDIT
        if ($template === 'error_db')
        {
            throw new Exception(implode("\n", (array) $message));
        }
        // END EDIT

        set_status_header($status_code);

        $message = '<p>'.implode('</p><p>', ( ! is_array($message)) ? array($message) : $message).'</p>';

        if (ob_get_level() > $this->ob_level + 1)
        {
            ob_end_flush();
        }
        ob_start();
        include(APPPATH.'errors/'.$template.'.php');
        $buffer = ob_get_contents();
        ob_end_clean();
        return $buffer;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用try/catch块检查错误并尝试运行另一个查询:

try {
    $this->db->get('table1');
} catch (Exception $e) {
    $this->db->get('table2');
}
Run Code Online (Sandbox Code Playgroud)

这是一种草率的解决方法,但它完成了工作.

您可能还想查看交易:

运行事务

要使用事务运行查询,您将使用 $this->db->trans_start()$this->db->trans_complete()函数,如下所示:

$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
$this->db->trans_complete();

您可以在启动/完成功能之间运行任意数量的查询,并且它们将根据任何给定查询的成功或失败提交或回滚.