문제

So i have this error when i have duplicate values while inserting data, now my query is correct, i've tried to run it in phpmyadmin, and works just fine, but kohana gives me errors, this is how my query looks like:

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

And in pure 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

So basicly i try to insert and on duplicate values i update, but for some reason kohana gives me error:

kohana Database_Exception [ 1062 ]: Duplicate entry

How can i remove this error?

도움이 되었습니까?

해결책

Perhaps try this approach by not specifying the query type:

$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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top