Search code examples
phpdatabaseactiverecorderror-handlingcodeigniter-2

Code Igniter catch errors on inserting data (Active Record)


I am inserting data into my database using the following code:

$this->db->set('event_id', $event_id);
...
$this->db->set('creator_id', $creator_id);

$this->db->insert('event');

How can I make sure the process was successful and show the user a confirmation message, else an error message?


Solution

  • Uhm, IIRC the method returns true if succesful, so you could go with a simple

    if($this->db->insert('event'))
    {
      echo 'Row succesfully inserted!';
    }
    

    Otherwise, you might always count the affected rows:

    //....
    $this->db->insert('event');
    if($this->db->affected_rows() > 0)
    {
      echo 'row succesfully inserted';
    }
    

    UPDATE after comment:

    I believe your three insert_batch() are on three different tables, so a check should be down on each one. Anyway, what's puzzling me is the reason behin this check..Query don't fail randomly: possibily they should never fail and when they do you'll know through errors (logged or dislayed).