【问题标题】:Codeigniter returning code 0 db errors without messageCodeigniter 返回代码 0 db 错误而没有消息
【发布时间】:2017-08-12 06:14:37
【问题描述】:

我有一个查询应该返回如下错误消息:

Error Number: 1451    
Cannot delete or update a parent row: a foreign key constraint fails (`sservice_dev_mercury`.`agent_accounts`, CONSTRAINT `agent_role_fk` FOREIGN KEY (`role`) REFERENCES `roles` (`id`))    
DELETE FROM `roles` WHERE `id` = '3'

此时db_debug 为真。当我把它变成假并使用时

$error = $this->db->error();
return $error;

我收到错误 0 并显示一条空消息。尝试获取错误时我缺少什么吗?这是查询:

public function delete($id){
     $this->db->trans_begin();
     $this->db->where('id',$id);
     $this->db->delete($this->table);
     $this->db->trans_complete();
     if($this->db->trans_status()===false){
        $this->db->trans_rollback();
        $error = $this->db->error();
        return $error;
     }else{
        $this->db->trans_commit();
        return true;
     }
}

有人可以看看有什么问题吗?

【问题讨论】:

  • 问题在于数据库表的关系。您能否发布两个表的架构并告诉我们其中一个是 $this->table
  • 哦。我知道它的桌子问题。我只是希望这个错误以消息的形式出现,而不是占据整个页面。我是故意这样设置的。
  • 您应该根据自己的需要自定义this method。由于行659,返回零。当然,您应该在不更改系统文件的情况下扩展类。也许你可以试试这种方式。
  • 嗨!感谢回复。如何扩展它?
  • 阅读docs and this full page,(尤其是this section)。

标签: php codeigniter mysqli transactions


【解决方案1】:

用户提到他想得到数据库事务中的错误。所以为此,我只找到了这个问题的解决方案,但它非常冗长:

try {
  $this->db->trans_begin();
  $res = $this->db->where('id',$id)->delete($this->table);   
  if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
  $this->db->trans_commit();
}
catch (Exception $e) {
  $this->db->trans_rollback();
  log_message('error', sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s', __CLASS__, __FUNCTION__, $e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)));
} 

请注意

  • 我正在使用 CI 的“手动事务”模式,
  • 我必须在每次查询后调用$this->db->_error_message()$this->db->_error_number(),因为它在 catch 块中返回一个空响应。

这样可以实现详细的错误处理。

Here 是参考链接。

【讨论】:

  • 谢谢!我会试试这个方法。到目前为止,其他方法似乎不起作用
  • @JianYA 可能是,我不确定。我会在测试后回复您。
  • 你好,新方法是使用$this->db->e​​rror();它只能在没有事务性项目(例如 trans_begins)的情况下工作,并且只能与一个查询一起工作。你知道它是否可以与多个一起使用吗?
猜你喜欢
  • 1970-01-01
  • 2016-01-30
  • 2019-07-23
  • 2013-10-31
  • 2011-08-28
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
相关资源
最近更新 更多