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

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

[eluser]Armchair Samurai[/eluser]
I'd ignore AR in this case and do something like this:
$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.

This post has a few suggestions on how to handle it:

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

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