Welcome Guest, Not a member yet? Register   Sign In
Active Record Insert Duplicate
#1

[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.
#2

[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.
#3

[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.
#4

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




Theme © iAndrew 2016 - Forum software by © MyBB