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

标签 php mysql database codeigniter error-handling

在 CodeIgniter 中,如果您的 sql 查询失败,那么脚本将停止运行并且您会收到错误消息。有什么方法可以让您尝试一个查询,如果失败了,那么您会默默地检测它并在用户不知道查询失败的情况下尝试不同的查询?

最佳答案

您可以修改 Exceptions 类以...抛出异常。只需在 application/core/ 中创建 MY_Exceptions.php:

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

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

try {
    $this->db->get('table1');
} catch (Exception $e) {
    $this->db->get('table2');
}

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

您可能想看看 transactions还有:

Running Transactions

To run your queries using transactions you will use the $this->db->trans_start() and $this->db->trans_complete() functions as follows:

$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();

You can run as many queries as you want between the start/complete functions and they will all be committed or rolled back based on success or failure of any given query.

关于php - 如何从 CodeIgniter 中失败的数据库查询中恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10407454/

相关文章:

php - 使用 PHP 和 MySQL 连接多个数据库

android - 以编程方式添加的按钮的不同点击

php - WordPress密码如何将用户密码与WordPress用户表密码进行比较?

php - 从mysql中选择多行并发送到php中的jquery post函数

php - 防止用户从表单向mysql提交数据两次

mysql - 移动表数据错误‘#1062 - 重复条目’

mysql - 如果它们具有相同的元素,则从一个表中合并组

javascript - 如何将树数据保存在数据库中进行分析

php - Phalcon教程报错PhalconException : TestController handler class cannot be loaded

javascript - 多列网格中,如何限制每列的元素数