Handle database error in CodeIgniter
I'm getting the following error while executing database query:
Error Number: 1062
Duplicate entry '1' for key 1
INSERT INTO `message_template` (`id`, `name`, `subject`, `detail`, `type`,
`status`, `create_date`)
VALUES (1, 'adaa', '', 'dss', 'SMS', 'Active', 开发者_运维技巧'2011-08-25 19:34:08')
Filename: C:\AppServ\www\ci\system\database\DB_driver.php
Line Number: 330
How can I get the error number (e.g. 1062
) to handlle error?
Thank you
That's an error coming from database.
You can hide in /application/config/database.php
$db['default']['db_debug'] = FALSE;
Else, you might want to take care of it. I suggest just checking if the value already exists:
$this->db->where('id', $id);
$query = $this->db->get('message_template');
$data = array(
'id' => $id,
'name' => $name,
'subject' => $subject,
'detail' => $detail,
'type' => $type,
'status' => $status,
'create_date' => $create_date
);
if($query->num_rows() > 0)
{
// the line already exists, so update
$this->db->where('id', $id);
$this->db->update('message_template', $data);
}
else
{
$this->db->insert('message_template', $data);
}
or, if you have the will to use raw queries, that should be slightly faster (I wouldn't really worry about a search by ID)
$sql = "INSERT INTO message_template
(id, name, subject, detail, type, status, create_date)
VALUES (1, " + $this->db->escape($name) + ", " + $this->db->escape($subject) + ", " + $this->db->escape($detail) + ", " + $this->db->escape($type) + ", " + $this->db->escape($status) + ", " + $this->db->escape($create_date) + ")
ON DUPLICATE KEY UPDATE name=" + $this->db->escape($name) + ", subject=" + $this->db->escape($subject) + ", detail=" + $this->db->escape($details) + ", type=" + $this->db->escape($type) + ", status=" + $this->db->escape($status) + ", create_date=" + $this->db->escape($create_date) + ";";
Otherwise, check out DataMapper ORM, so all your database things are automatically taken care of.
精彩评论