1

Sorry for my english but please i need help i have a problem when i'm trying to catch an insert query

i have a table Employe with 3 primary keys (Matricule , CIN , name)

i want to catch the exception when i add a new employe with duplicated values

My Model

  function insert_Employe($donnees){
   try{
    $this->db->insert('Employe',$donnees);
    return 'employe enregistré avec succes';
   }catch(Exception $e)
   {
       return $e->getMessage();
   }
}

My controller

  function nouveau(){
    if(!$this->offres->_isLogged() || !$this->input->post('Ajax')==1){
        redirect(base_url().'users');
    }
    $values = $this->_get_values();
    try{
    $message = $this->employe->insert_Employe($values);
    echo $message;
    }catch(Exception $e){
        echo $e->getMessage();
    }
}

i can't catch the exception

bouchnina
  • 11
  • 1
  • 4
  • So `$this->db->insert()` causes an exception that you catch in `insert_Employe()` and you wonder why the latter doesn't throw an exception? – kero Mar 24 '14 at 19:35
  • The Exception handle when i insert a duplicated values i would to catch this exception to inform user that he has to change the duplicated value that cause the problem – bouchnina Mar 24 '14 at 19:40

1 Answers1

2

This will never throw an exception:

$this->db->insert('Employe',$donnees);

So you'll never catch an exception like that. If the insert() method fails it will generate display a custom error if $db['default']['db_debug'] is set to TRUE on database.config or simply return FALSE otherwise.

Your best bet is to check for errors when doing your DB operations:

$error = $this->db->_error_message()
if(!empty($error)) {
  throw new Exception('Your message');
}
Gustavo Rubio
  • 10,209
  • 8
  • 39
  • 57