I did what you describe using a while loop so that each iteration creates a MySQL statement that affects one row. Inside the loop, I run mysql_affected_rows () and then increment the counter depending on whether the return value was 0 or 1. At the end of the loop, I repeat both variables for viewing.
The full wording of the MySQL Docs regarding the mysql_affected_rows function (note that 3 possible values ββare returned - 0, 1, or 2):
For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected row value in the row is 1 if the row is inserted as a new row, 2 if the existing row is updated, and 0 if the existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag, the affected-rows value is 1 (not 0) if the existing row is set to its current values.
( Sidenote ). I set $ countUpdate and $ countInsert and $ countUpdateNoChange to 0 before the while loop):
Here is the code I developed that works great for me:
while (conditions...) { $sql = "INSERT INTO test_table (control_number, name) VALUES ('123', 'Bob') ON DUPLICATE KEY UPDATE name = 'Bob'"; mysql_query($sql) OR die('Error: '. mysql_error()); $recordModType = mysql_affected_rows(); if ($recordModType == 0) { $countUpdateNoChange++; }elseif($recordModType == 1){ $countInsert++; }elseif($recordModType == 2){ $countUpdate++; }; }; echo $countInsert." rows inserted<br>"; echo $countUpdateNoChange." rows updated but no data affected<br>"; echo $countUpdate." rows updated with new data<br><br>";
Hopefully I didnβt make any typos as I recreated them for sharing, deleting my sensitive data.
Hope this helps someone. Good luck codes!
source share