php 数据库错误 处理,php – 在CodeIgniter中处理数据库错误

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

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)以处理错误?

谢谢

解决方法:

这是来自数据库的错误.

您可以隐藏在/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,以便自动处理所有数据库事务.

标签:php,sql,codeigniter,error-handling

来源: https://codeday.me/bug/20190723/1515261.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值