Php 如何在CodeIgniter中从失败的数据库查询中恢复?
在CodeIgniter中,如果您的sql查询失败,那么脚本将停止运行,您将得到一个错误。有没有办法让您可以尝试一个查询,如果查询失败,您可以默默地检测它并尝试另一个查询,而用户不知道查询失败?您可以使用以下方法访问数据库错误:Php 如何在CodeIgniter中从失败的数据库查询中恢复?,php,mysql,database,codeigniter,error-handling,Php,Mysql,Database,Codeigniter,Error Handling,在CodeIgniter中,如果您的sql查询失败,那么脚本将停止运行,您将得到一个错误。有没有办法让您可以尝试一个查询,如果查询失败,您可以默默地检测它并尝试另一个查询,而用户不知道查询失败?您可以使用以下方法访问数据库错误: $this->db->_error_message() $this->db->_error_number() 您可以将Exceptions类修改为。。。抛出异常。只需在application/core/中创建MY_Exceptions.php: class MY_Ex
$this->db->_error_message()代码>
$this->db->_error_number()代码>
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;
}
}
这是一种草率的解决方法,但它能完成工作
您可能还想看看:
运行事务
要使用事务运行查询,您将使用
$this->db->trans\u start()
和$this->db->trans\u complete()
的功能如下
如下:
$this->db->trans_start()代码>
$this->db->query('SQL查询…')代码>
$this->db->query('另一个查询…')代码>
$this->db->query('还有另一个查询…)代码>
$this->db->trans_complete()代码>
您可以在开始/完成之间运行任意数量的查询
函数,它们都将根据
任何给定查询的成功或失败
您可以在他们的官方论坛上查看此帖子,讨论并建议针对此特定主题的解决方案:
实现这一目标的方法之一是
首先
Set ['db_debug'] = FALSE; in config/database.php
那么
在您的模型中-
public function attempt_one($data) {
//build your query ....
$query_result = $this->db->insert('table_name');
if(!$query_result) {
$this->error = $this->db->_error_message();
$this->errorno = $this->db->_error_number();
return false;
}
return $something;
}
public function attempt_two() {
//another query goes in here ...
}
在控制器中-
public function someAction ()
{
//some code
$data = $some_data;
$result1 = $this->yourmodel->attempt_one($data);
if($result1 === false)
{
//Some code to send an email alert that first query failed with error message
//and/or log the error message/ number
$result2 = $this->yourmodel->attempt_two($data);
}
}
只用
$this->db->simple_query()
而不是
$this->db->query()
简单查询将返回true/false。只是好奇在什么情况下查询失败?@zerkms在Unique
列中插入一个值,如果失败,我只想生成一个新值并重试,而不是失败。这很有意义。我想知道CI没有使用异常,因为这才是真正的答案,我不敢相信我在使用CI的这些年里从未使用过这个设置。我可以确认这也有效。
$this->db->query()