我想在cakephp中显示数据库的错误。如何向用户显示“sql错误”消息。这是我的代码。在这段代码中,我收到了数据库错误。但我希望向用户显示正确的消息而不是数据库错误。
public function edit_mothertongue(){
$motherTongue=array();
if($this->request->is('post')){
foreach ($this->request->data as $key => $value) {
$motherTongue[$key]=$value;
}
if(!empty($motherTongue)){
App::import('Model','MotherTongue');
$this->MotherTongue=new MotherTongue();
try{
if($this->MotherTongue->save($motherTongue)){
echo "Record saved";
}else{
echo "Record not saved";
}
}
catch(Exception $e){
echo $e->getMessage(); // I want to display error message of sql.
}
}
}
}
答案 0 :(得分:1)
如果要显示信息,则需要使用视图。要将信息从控制器传递到视图,请使用set方法。
$this->set('errormsg', $e->getMessage());
然后在您的视图中使用$errormsg
。
答案 1 :(得分:1)
如果您想使用AJAX,可以这样设置:
$this->set('_serialize', array('errormsg'));
如果您正在寻找JSON的输出
然而,使用AJAX超出了这个问题的范围。