0

I can normally check if a record is inserted using affected_rows() but this record I am trying to insert causes an duplicate entry error and it makes the program execution stop.

Example: Using CodeIgniter

//Insert description                
$this->db->query("
INSERT INTO comments_descriptions
(comment_id, description)
VALUES
(?, ?)          
", array($commentID, $description));

This part is never reached:

if ($this->db->affected_rows() !== 1){
    // Do stuff...
}

My AJAX call for this inserts only returns the number 500 and Firebug shows an internal server error every time I try to insert a duplicate statement. I have tried surrounding the insert in a try/catch block and still the error is not caught. Please help.

boompow
  • 131
  • 1
  • 12

1 Answers1

0

comment_id is set as unique so inputing multiple rows with the same value is impossible which results in the duplicate entry error!

It is unclear how your table is structured but you would add the description to an existing comment_id, avoiding this duplicate entry error.

Skewled
  • 783
  • 4
  • 12
  • I do want a duplicate entry check, that is exactly why the field has a `unique` constraint. I want to avoid doing an extra select statement and that is the reason the `unique` field is there. – boompow Apr 30 '14 at 17:09
  • You should just use the select query it won't take the system that much to be noticeable, you can't bypass the error as it throws a 500(Internal Server Error) you can't recover from that. Also, it's why I suggested that you redo the table structure and make comment_id a foreign key for linking to a comment, then each comment would contain a unique key, then you could scan for duplicates later on if you wanted. – Skewled Apr 30 '14 at 18:53
  • Thanks a lot for all the help you've given me. I just find it weird that a duplicate entry creates a 500 error instead of one being able to handle it. – boompow Apr 30 '14 at 19:52
  • @boompow I did some reading have you looked into `REPLACE INTO`, I think it would fix this issues. If it detects a row with that ID it say's that it can delete and insert the new data. Worth giving a try. – Skewled May 01 '14 at 02:30