Using PHP PDO, is there a way to distinguish the difference between an UPDATE failing, and an UPDATE running successfully but setting a field to its existing value?
$sql = 'UPDATE table SET column = :column WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(':column', $column, PDO::PARAM_STR);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$statement->execute();
$RowsUpdated = $statement->rowCount();
echo '$RowsUpdated = '.$RowsUpdated.'<br />';
The above code sets $RowsUpdated to 1 if the value of $column is a new value, and sets it to 0 if it's the same as the existing value. I tried to force an error by altering the SQL statement, but it never returns a non-numeric value (such as NULL or False) and is never less than 0.
When SELECT'ing rows with COUNT(*), fetchColumn() returns the number of rows if there are any, or 0 if there aren't any, or something else if there's an error. So I'm able to use ($countRowsSelected > 0) to detect rows, ($countRowsSelected === "0") to detect no rows, and ELSE to detect an error.
Is it possible to do this with an UPDATE? In addition to the UPDATE, I want to trigger secondary actions but only if the saved value has CHANGED, so I want this:
if ($RowsUpdated > 0) {
// We go a NEW value, let's do a little dance
} else if ($RowsUpdated === "0") {
// It saved, but the value was unchanged
} else {
// Error!
}
I tried adding PDO::MYSQL_ATTR_FOUND_ROWS => true to my PDO, but this caused rowCount() to return 1 regardless of whether or not the value changed, so it didn't help.