I am using MariaDB (or MySQL if you like) and was looking for a solution to this question and came across this post. It answers the question in part, but didn't quite resolve what I was trying to achieve. And that question as I read it from DanFromGermany is: how many records were added to the database and how many were updated in the database during my transaction or transactions.
So using some of the helpful elements in this post, I came up with this solution:
In my actual code I have wrapped it all in try/catch where needed and assumed that $dbx is an instantiated PDO mysql database object.
/*
Get the current table row count
(it's our starting point, so any inserted row will increase the count)
*/
$stmt = $dbx->query("SELECT COUNT(*) FROM `destination_table`");
$row = $stmt->fetch(PDO::FETCH_NUM);
$startCount = $row[0];
$stmt = null;
/*
Set an iteration counter
(
I was using a prepared statement looping through
INSERT / ON DUPLICATE KEY UPDATE, so want to check each loop for any change
)
*/
$countAnAction = 0;
/*
Prepare the INSERT with ON DUPLICATE KEY UPDATE for each line to process
(assuming `a` is the key, regardless of type)
*/
$stmt = $dbx->prepare("
INSERT INTO `destination_table` (`a`,`b`)
VALUES(:a, :b1)
ON DUPLICATE KEY UPDATE `b` = :b2
");
$stmt->bindParam('a', $a, PDO::PARAM_STR);
$stmt->bindParam('b1', $b, PDO::PARAM_STR);
$stmt->bindParam('b2', $b, PDO::PARAM_STR); # set update value if a exists
// Assume we have an associative array of 'a', 'b' values passed to process
foreach($inputRowToProcess as $arrVals)
{
# Set our prepared values from the array elements
$a = $arrVals['a'];
$b = $arrVals['b'];
$stmt->execute();
/* Now check if something happened and increment $countAnAction
(
$stmt->rowCount() on MySQL can be 1 or 2, depending on the action
based off a value greater than zero, update the row count by 1
)
*/
if($stmt->rowCount() > 0)
{
$countAnAction += 1;
}
}
$stmt = null;
// Now we get the count of rows in the destination table after the process has finished
$stmt = $dbx->query("SELECT COUNT(*) FROM `destination_table`");
$row = $stmt->fetch(PDO::FETCH_NUM);
$endCount = $row[0];
$stmt = null;
// Finally apply some math to the various elements to determine inserted count and updated count
$insertedRows = $endCount - $startCount;
$updatedRows = ($endCount - $startCount) + $countAnAction;