php Codeigniter - 使用活动记录时处理错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2204140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Codeigniter - handling errors when using active record
提问by Sergio
I am putting together a few models for my codeigniter site and can't seem to find any word in the documentation of how to handle errors that could occur when using the Active Record system.
我正在为我的 codeigniter 站点组合一些模型,但似乎在文档中找不到任何关于如何处理使用 Active Record 系统时可能发生的错误的词。
The documentation demonstrates how to perform CRUD along with some relatively involved queries but no where along the line is error handling discussed. I have done a quick google search and it would appear that the Active Record classes do not throw exceptions. Is this the case? No try catch then...
该文档演示了如何执行 CRUD 以及一些相对涉及的查询,但没有讨论错误处理。我做了一个快速的谷歌搜索,看起来 Active Record 类不会抛出异常。是这种情况吗?没有尝试捕捉然后...
So, how do you code to handle database errors in codeigniter? (failed connection, duplicate key, broken referential integrity, truncation, bad data types etc etc)
那么,您如何编写代码来处理 codeigniter 中的数据库错误?(失败的连接、重复的密钥、破坏的参照完整性、截断、错误的数据类型等)
回答by emmychan
Whether you're using the active record class or not, you can access database errors using $this->db->_error_message()and $this->db->_error_number().
无论您是否使用活动记录类,您都可以使用$this->db->_error_message()和访问数据库错误$this->db->_error_number()。
If you're using a mysql database, these functions are equivalent to mysql_error()and mysql_errno()respectively. You can check out these functions by looking at the source code for the database driver for the database you're using. They're located in system/database/drivers.
如果您使用的是 mysql 数据库,则这些函数分别等效于mysql_error()和mysql_errno()。您可以通过查看您正在使用的数据库的数据库驱动程序的源代码来检查这些函数。它们位于系统/数据库/驱动程序中。
So, after you run a query, you can check for errors using something like:
因此,在运行查询后,您可以使用以下方法检查错误:
if ($this->db->_error_message()) \handle error
回答by Peter Drinnan
Straight from the CodeIgniter support forum:
直接来自 CodeIgniter 支持论坛:
$res = $this->db->query($str);
if (!$res) {
// if query returns null
$msg = $this->db->_error_message();
$num = $this->db->_error_number();
$data['msg'] = "Error(".$num.") ".$msg;
$this->load->view('customers_edit_view',$data);
}
Note that you can also log Active Record errors by going into your CI app config file and setting the following:
请注意,您还可以通过进入 CI 应用程序配置文件并设置以下内容来记录 Active Record 错误:
$config['log_threshold'] = 1;

