CodeIgniter Forums
Active Record Insert Duplicate - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Active Record Insert Duplicate (/thread-6455.html)



Active Record Insert Duplicate - El Forum - 02-27-2008

[eluser]Firestorm ZERO[/eluser]
Is there a way to handle the SQL error when I do a INSERT to the database that failed due to a duplicate entry? So that I give a more friendly error message then the default CI error.


Active Record Insert Duplicate - El Forum - 02-27-2008

[eluser]Armchair Samurai[/eluser]
I'd ignore AR in this case and do something like this:
Code:
$sql = "INSERT INTO table_name (foo, bar)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE foo = foo";
$this->db->query($sql, array($var1, $var2));

return $this->db->affected_rows() == 1 ? TRUE : FALSE;
and handle the error in the controller if it returns FALSE.


Active Record Insert Duplicate - El Forum - 02-28-2008

[eluser]ontguy[/eluser]
This post has a few suggestions on how to handle it:
http://ellislab.com/forums/viewthread/49739/

I think checking if the value exists before inserting is the way to go.


Active Record Insert Duplicate - El Forum - 02-29-2008

[eluser]Rascal2pt0[/eluser]
doesn't active record throw an exception.?

Other than using the procedural code as posted by Armchair Samurai, catching that exception and then doing as you well is the next best thing.