2014-09-21 142 views
0

我想在cakephp中顯示數據庫錯誤。如何向用戶顯示「sql error」消息。這是我的代碼。在這段代碼中,我收到了數據庫錯誤。但我想向用戶顯示正確的消息而不是數據庫錯誤。Cakephp 2.5.4:數據庫錯誤錯誤:SQLSTATE [23000]:完整性約束違規:1062重複條目

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. 
      } 
     }  
    }  

} 

回答

1

當你想顯示信息時,你需要使用一個視圖。要將信息從控制器傳遞到視圖,請使用方法set

$this->set('errormsg', $e->getMessage()); 

然後在您的視圖中使用$errormsg

+0

如果我想通過ajax顯示錯誤信息,那我該怎麼辦?請回答這個問題,我將不勝感激。 – 2014-09-21 13:50:26

1

如果你想使用AJAX可以將其設置是這樣的:

 $this->set('_serialize', array('errormsg')); 

如果您正在尋找在JSON

輸出但是使用AJAX超出了這個問題的範圍。

+0

非常感謝 – 2014-09-25 15:45:34

相關問題