views:

176

answers:

1

I am using PHP and MySQL.

If I use an INSERT ON DUPLICATE UPDATE SQL statement, then how do I know if the last operation was an successful insert and not an update or unsuccessful insert?

The assumptions are the table in question does not use an auto increment, so I can't use a mysql_insert_id to help me find out.

+6  A: 

You'll want to check mysql_affected_rows() which will return 1 on an insert and 2 on an update. As per the mysql documentation.

if (mysql_affected_rows() == 1) //INSERT
elseif (mysql_affected_row() == 2) //UPDATE

Unless the update does not change anything, in which case it will return 0.

Cahlroisse
Would mysql_affected_rows() really return 2 on UPDATE?
Alix Axel
I ran several tests and that's what it returned for me every time it did an update instead of an insert. Whether I was updating one column or all columns. I'm assuming it's for the reason I said, but I'm not entirely sure.
Cahlroisse
It's documented at http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.htmlWith ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated.
dmercredi
Very nice, thank you for the reference.
Alix Axel
@dmercredi Thanks! So, it's actually just because it's designed that way, not for the reasoning I made up. Answer edited to have accurate info.
Cahlroisse
uhm, theoretically an INSERT could conflict with multiple rows indexes (in case the table has more than one UNIQUE index). so, in these cases we just can't know how many rows we have updated? I'd expect it to return the number of updated rows in case of index conflicts but that's another discussion that does not belong here
Saggi Malachi