数据库错误重复输入

时间:2012-02-04 12:34:51

标签: kohana kohana-3 kohana-db

所以当我在插入数据时有重复值时出现此错误,现在我的查询是正确的,我试图在phpmyadmin中运行它,并且工作正常,但kohana给了我错误,这是我的查询看起来如何像:

DB::query(Database::INSERT, 'INSERT INTO `views` ( user_id, viewer_id, username, picture, view_time, view_count) 
                    VALUES ("'.$this->request->param('id2').'", "'.$user->id.'", "'.$user->username.'", "'.$user->picture.'", '.DB::expr('NOW()').', "1")
                    ON DUPLICATE KEY UPDATE `view_time` = NOW(), `view_count` = view_count +1

在纯sql中:

INSERT INTO `views` ( user_id, viewer_id, username, picture, view_time, view_count )
VALUES (
"134173", "139173", "username", "pic.jpg", NOW( ) , "1"
) ON DUPLICATE
KEY UPDATE `view_time` = NOW( ) ,
`view_count` = view_count +1

所以基本上我尝试插入并重复更新值,但由于某种原因,kohana给了我错误:

kohana Database_Exception [ 1062 ]: Duplicate entry

如何删除此错误?

1 个答案:

答案 0 :(得分:2)

也许通过不指定查询类型来尝试这种方法:

$query = " 
  INSERT INTO `views` (user_id, viewer_id, username, picture, view_time, view_count)
  VALUES (%d, %d, '%s', '%s', %s, %d)
  ON DUPLICATE KEY UPDATE `view_time` = %s, `view_count` = view_count + 1";

$query = sprintf($query, $this->request->param('id2'), $user->id, $user->username, $user->picture, DB::expr('NOW()'), 1, DB::expr('NOW()'));

$result = Database::instance()->query(NULL, $query);