Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a MySQL update query succeeded when the data passed in the query is the same as what is already in the database?

Let's say you have a form with pre-populated data from your database, and you allow your users to make changes and save the form. If the user clicks the save button without making any changes, MySQL will not actually perform a write operation, and therefore the affected_rows will return 0.

I understand the behavior, but what is the best practice for determining if an update failed, other than checking for the number of affected_rows?

What is the best practice for differentiating between an update that actually failed, and one that "succeeded" but resulted in 0 affected_rows so that I can provide feedback to the user?

like image 491
Kyle Noland Avatar asked May 25 '11 21:05

Kyle Noland


2 Answers

Just check if no errors occurred after execution of query.
If you use mysql, check mysql_error():
if (!mysql_error()) print 'all is fine';
Same for mysqli.

like image 165
OZ_ Avatar answered Oct 13 '22 15:10

OZ_


Variation 1:

mysql_query() or die('error');

Variation 2:

$conn = mysql_query();
if(!$conn) {//Error code here}

Variation 3:

try {
  $conn = mysql_query();
  if (!$conn) throw new Exception("mysql Error");
} catch(Exception $e) {
  echo $e->getMessage();
}
like image 32
Racooon Avatar answered Oct 13 '22 16:10

Racooon