处理CodeIgniter中的数据库错误

时间:2011-08-25 12:35:49

标签: php sql codeigniter error-handling

执行数据库查询时出现以下错误:

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

如何获取错误编号(例如1062)以处理错误?

谢谢

1 个答案:

答案 0 :(得分:9)

这是来自数据库的错误。

您可以隐藏在/application/config/database.php

$db['default']['db_debug'] = FALSE; 

否则,你可能想要照顾它。我建议只检查值是否已经存在:

$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);
}

或者,如果您有使用原始查询的意愿,那应该稍快一点(我不会真的担心按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) + ";";

否则,请查看DataMapper ORM,以便自动处理所有数据库内容。