Welcome Guest, Not a member yet? Register   Sign In
Database class - catch insert error
#1

[eluser]Zeff[/eluser]
Hi all,

When I use
Code:
$this->db->insert('mytable', $mydata)
to insert data into a mysql table, sometimes I get an error like
Code:
'A Database Error Occurred ... Error Number: 1062 ... Duplicate entry 'zeff' for key 1'
, because I don't use an autoincrement primary key but just a unique varchar field.
I have read that 'write' actions only return true or false, but isn't there a manner to intercept the 1062 error code and show the user a nicely styled paged saying 'the record already exists'?

Many thanks in advance!

Zeff
#2

[eluser]Zeff[/eluser]
No solution yet ...

So I choose the following workaround: (maybe it can help others :-))

Code:
$sql ="SELECT * WHERE `uid` ='" . $uid . "'";
where the uid field is my primary key field.
Now with the following code, I handle duplicate key problems:
Code:
if($this->db->simple_query($sql)){
    if($this->db->insert('accounts', $data)){
        $this->data["content"]  = "<div class='ok'>Record successfully added...</div>";
    }else{
        $this->data["content"]  = "<div class='error'>Insert of new record failed!</div>";
    }
}else{
    $this->data["content"] = "<div class='error'>Record already exists.</div>";
}
I do not use a model here, since I just use simple native active record functions...




Theme © iAndrew 2016 - Forum software by © MyBB