在 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/