CodeIngniter中的数据库错误处理问题 [英] Database Error Handling problem in CodeIngniter
本文介绍了CodeIngniter中的数据库错误处理问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以使用 $ this- > db-> escape()
函数来解决我的数据问题,但我只是想知道:为什么TRY / CATCH不能捕获这个错误!
控制器代码:
$ this-> load-> model('user_model');
$ result = $ this-> user_model-> test_user(tes'ti);
型号代码:
function test_user($ username){
try {
$ query_str =SELECT * FROM tbl_user WHERE username ='。$ username。';
$ result = $ this-> db-> query($ query_str);
return $ result;
} catch(异常$ e){
return;
}
}
输出:
发生数据库错误
错误号:1064
您的SQL中有错误句法;检查对应于您的MySQL服务器版本的手册,以便在第1行使用ti附近的正确语法
SELECT * FROM tbl_user WHERE username ='tes'ti'
让我知道,如果我做错了,我犯了一个错误!
谢谢你的时间和帮助他人。 ;)
解决方案
如果有一些mysql错误,您需要抛出异常:
try {
$ query_str =SELECT * FROM tbl_user WHERE username ='。$ username。';
$ result = $ this-> db-> query($ query_str);
if(!$ result)
{
throw new Exception('query in query');
返回false;
}
return $ result;
} catch(异常$ e){
return;
}
I use CodeIgniter as my web application framework. I used a simple Try/Catch and I sent a sample value to test it, and it failed!
I know I can use $this->db->escape()
function to solve my data problem but I just want to know: Why TRY/CATCH can not catch this error!
Controler code:
$this->load->model('user_model');
$result = $this->user_model->test_user("tes'ti");
Model code:
function test_user($username){
try {
$query_str = "SELECT * FROM tbl_user WHERE username = '".$username."'";
$result = $this->db->query($query_str);
return $result;
} catch (Exception $e) {
return;
}
}
Output:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ti'' at line 1
SELECT * FROM tbl_user WHERE username = 'tes'ti'
Let me know, where I made a mistake, if I did!
Thank you for your time and helping others. ;)
解决方案
You need to throw an exception if there was some mysql error:
try {
$query_str = "SELECT * FROM tbl_user WHERE username = '".$username."'";
$result = $this->db->query($query_str);
if (!$result)
{
throw new Exception('error in query');
return false;
}
return $result;
} catch (Exception $e) {
return;
}
这篇关于CodeIngniter中的数据库错误处理问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文