I have always struggled with a fairly basic concept in my PHP INSERT/UPDATE code. Should I always be checking for the number of affected rows after every INSERT/UPDATE because in the vast majority of times I am only ever performing one INSERT/UPDATE and it seems to cause more problems than it fixes by checking that only one row was affected.
Below is my standard code to perform the INSERT/UPDATE and this code fails if the user is updating a record without changing anything because the affected rows will be 0. I could write code to check that at least one field has changed but on large forms this seems very clunky and was wondering if it is really worth it because I have never really ever caught any errors by checking this number anyway.
<?php
$whereSql = '';
$groupSql = 'INSERT INTO';
if(isset($_POST['id']) && is_numeric($_POST['id'])){
$groupSql = 'UPDATE';
$whereSql = 'WHERE id = ' . $_POST['id'];
}
$groupSql .= ' sometable SET name="' . $name . '" ' . $whereSql;
$groupDb = mysqli_query($groupSql, $dbObject) or die("Login DB error:".mysql_error());
if(mysqli_affected_rows($dbObject) == 1){
//redirect
}else{
die('System Error');
}
You should be checking return values on queries. A select/update query which affects/returns no rows is NOT an error condition, it's simply an empty result set, or an update which happened to affect nothing.
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Consider a user signup system which checks for the existence of a matching username:
SELECT id FROM users WHERE username='foo';
if the user foo
does not exist, your system will barf and claim an error occurred. But an empty result set is NOT an error. It simply means the username is available for user.
Same for a system that handles grades:
UPDATE students SET failed=true WHERE score < 50;
getting 0 affected rows is NOT a failure. It just means all the students passed.
I would recommend checking if the query has failed, and if not, then if there was more than one row affected.
$groupDb = mysql_query($groupSql, $dbObject);
if (false === $groupDb) {
die("Login DB error:".mysql_error())
if (mysql_affected_rows($dbObject) > 1) {
die('System Error: failed to ' . $action . ' a document Group');
} else {
//redirect
}
This way you will redirect only in case of successful queries and if there was less than 2 rows affected (if that is important to you).