PHP Update giving error if no data is edited
Thanks for asking me to make my question clearer.
I have a form which is used to save content in a database. The user is also allowed to update any content by editing the fields in the form and submitting it.
The update query looks something like this:-
$res = mysql_query("UPDATE freight SET .... WHERE id='$id'") or die ( mysql_error());
if(mysql_affected_rows() > 0){
//do some stuff
return true;
}
else{
return false;
}
Now my problem is this: If the user changes some field while updating the form, mysql_affected_rows() is > 0 so I am able to "//do some stuff". But if the user does not change any field in the form and simply submits, mysql_affected_rows return 0 and I reach the false block.
I was under the impression that UPDATE should overwrite every time thereby mysql_affected_rows() should return 1 irrespective of whether any fields have been changed or not.
I use the return value to display an appropriate success or error message in the screen. Hence this is a serious bug.
Can you suggest whats the right way to achieve the correct functionali开发者_高级运维ty?
Thanks, Vish
mysql_affected rows()
-1 will be returned if the query itself can not be issued to the server, possibly because of syntax error AND if the last query was not either an INSERT or UPDATE statement.
When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.
so your solution can be achieved by below logic ( but this is not safe)
if(mysql_affected_rows()!=-1){
}
if( $_POST['message'] != '' ) {
// add the field to your query
} else { // this is optional
// don't add it to your query
}
// do the mysql update here
精彩评论