Amuk Saxena
Amuk Saxena

Reputation: 1571

Cakephp 2.5.4: Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I want to show error for database in cakephp. How can I display a message of "sql error" to the users. This is my code. In this code, I am getting Database Error. But I want to show proper message to the user instead of database error.

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

}

Upvotes: 0

Views: 1016

Answers (2)

Anup Kale
Anup Kale

Reputation: 41

If you want to use AJAX you can set it like this:

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

If you are looking for an output in JSON

However using AJAX is out of scope of this question.

Upvotes: 1

AgRizzo
AgRizzo

Reputation: 5271

When you want to display information, you need to use a view. To pass information from the controller to the view use the set method.

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

Then use $errormsg in your view.

Upvotes: 1

Related Questions