php 当查询中传递的数据与数据库中已有的数据相同时,如何确定MySQL更新查询是否成功?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6131304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:25:51  来源:igfitidea点击:

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?

phpmysqlerror-handlingrows-affected

提问by Kyle Noland

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.

假设您有一个包含来自数据库的预填充数据的表单,并且您允许您的用户进行更改并保存该表单。如果用户在没有做任何更改的情况下单击保存按钮,MySQL 将不会实际执行写操作,因此受影响的行将返回 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?

区分实际失败的更新和“成功”但结果为 0 影响的更新以便我可以向用户提供反馈的最佳实践是什么?

采纳答案by OZ_

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.

只需检查执行查询后是否发生错误。
如果使用mysql,检查mysql_error()
if (!mysql_error()) print 'all is fine';
同为mysqli的

回答by Mel

[affected_rows()][1] is -1 if a query fails, not zero.

[1]: http://www.php.net/manual/en/function.mysql-affected-rows.php

[affected_rows()][1] 如果查询失败,则为 -1,而不是零。

[1]:http: //www.php.net/manual/en/function.mysql-affected-rows.php

It may return 0 if no changes were made to the row (same values), or if mysql didnt find a row to update. It will only return -1 due syntax erro

如果没有对行进行更改(相同的值),或者如果 mysql 没有找到要更新的行,它可能返回 0。它只会返回 -1 由于语法错误

回答by Racooon

Variation 1:

变化1:

mysql_query() or die('error');

Variation 2:

变体2:

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

Variation 3:

变化3:

try {
  $conn = mysql_query();
  if (!$conn) throw new Exception("mysql Error");
} catch(Exception $e) {
  echo $e->getMessage();
}

回答by James

if the update "fails" due to syntax error, or other mysql will return an error code on the actual mysql query and affected_rows will return with yet another error.

如果更新由于语法错误而“失败”,或者其他 mysql 将在实际 mysql 查询中返回错误代码,而受影响的行将返回另一个错误。

Php for example:

以 PHP 为例:

$qry = mysql_query("update blah where IamaSyntaxerror,33");
if ($qry === FALSE) { echo "an error has occured"; }

else  { mysql_affected_rows() == 0  means no updates occured