如何在 CodeIgniter PHP 中捕获数据库错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17923382/
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
How to catch DB errors in CodeIgniter PHP
提问by Joy
I am new to CodeIgniter, PHP and MySQL. I want to handle the DB generated errors. From one of the post in Stackoverflow, I knew that by following statement one can catch the error.
我是 CodeIgniter、PHP 和 MySQL 的新手。我想处理数据库生成的错误。从 Stackoverflow 中的一篇文章中,我知道通过以下语句可以捕获错误。
$this->db->_error_message();
But I cannot figure out the exact syntax of using that. Suppose I want to update the records of table named "table_name" by the following statement:
但我无法弄清楚使用它的确切语法。假设我想通过以下语句更新名为“table_name”的表的记录:
$array['rank']="8";
$array['class']="XII";
$this->db->where('roll_no',$roll_no);
$this->db->update("table_name", $array);
Here in the above code I want to catch the DB error whenever any DB level violation occurs i.e. either field name is not valid or some unique constraint violation occurs. If anyone helps me to fix that I would be really grateful. Thank you.
在上面的代码中,我想在发生任何 DB 级别违规时捕获 DB 错误,即字段名称无效或发生某些唯一约束违规。如果有人帮我解决这个问题,我将不胜感激。谢谢你。
回答by Rajeev Ranjan
codeIgniter has functions for it
codeIgniter 有它的功能
$this->db->_error_message();
$this->db->_error_number();
if(!$this->db->update("table_name", $array))
{
$this->db->_error_message();
$this->db->_error_number();
}
回答by Erman Belegu
You can debug the database error on database configuration in (config/database.php) like this:
您可以在 (config/database.php) 中调试数据库配置中的数据库错误,如下所示:
$db['default']['db_debug'] = TRUE;
More info read here
更多信息请阅读这里
Also you can use Profiler to see all the queries and their speed. In controller you can put this:
您也可以使用 Profiler 查看所有查询及其速度。在控制器中,你可以把这个:
$this->output->enable_profiler(TRUE);
More information read here
更多信息请阅读这里
回答by Sultan
On Codeigniter version 2,
在 Codeigniter 版本 2 上,
$this->db->_error_message();
$this->db->_error_number();
On Codeigniter version 3,
在 Codeigniter 版本 3 上,
$db_error = $this->db->error();
echo '<pre>';print_r($db_error);echo '</pre>';