Hi,

To solve this you can use the REPLACE command.

Regards,

Laercio.

-----Original Message-----
From: news [mailto:[EMAIL PROTECTED] On Behalf Of Harald Fuchs
Sent: quinta-feira, 30 de setembro de 2004 08:25
To: [EMAIL PROTECTED]
Subject: Re: (if !update then insert) sequence - result Duplicate key :(

In article <[EMAIL PROTECTED]>,
"Aleksandr V. Dyomin" <[EMAIL PROTECTED]> writes:

> $key='somekeyvalue';
> dbquery("update sometable set count=count+1 where keyfield='$key'");
> if(mysql_affected_rows()<1)
>       dbquery('insert into sometable set keyfield='$key', count=1');
> ---

> First question: this is good method?

It's good if you expect the UPDATE normally to succeed.  Otherwise, you
should first try the INSERT.

> Second... My script work on many different hosts with different 
> hardware, os(only Linux or FreeBSD), and different PHP and MySQL 
> version. It works fine excepting one thing... Sometime happens errors
> like:
> MySQL: Duplicate entry 'somekeyvalue' for key 1, query was: insert 
> into sometable set keyfield='somekeyvalue', count=1

> Why this happens? On some hosts this messageis very rare, but on 
> others
> - so often... I cant understand reason :(

You have a race condition:

* Client 1 tries UPDATE, sees that it fails
* Client 2 tries UPDATE, sees that it fails
* Client 1 does INSERT - okay
* Client 2 does INSERT - duplictae key error

If you think this happens seldom, do the following:

1. Try UPDATE
2. If it fails: try INSERT
3. If it fails due to a duplicate key error: repeat step 1


--
MySQL General Mailing List
For list archives: http://lists.mysql.com/mysql
To unsubscribe:
http://lists.mysql.com/[EMAIL PROTECTED]


-- 
MySQL General Mailing List
For list archives: http://lists.mysql.com/mysql
To unsubscribe:    http://lists.mysql.com/[EMAIL PROTECTED]

Reply via email to