如何知道 MySQL UPDATE 查询是否因为提供的信息与数据库中已有的数据匹配而失败?
我有一个查询,用户在文本区域字段中键入文本块。他们能够将此信息保存在数据库中。问题是,如果他们没有更改信息或者信息与数据库中已有的数据匹配,我会收到受影响行的“0”。通常,当没有受影响的行时,我会显示一条错误,指出查询失败。我如何“知道”0 个受影响的行是因为数据已经存在,以便我可以显示更具体的错误?
I have a query where the user types a block of text in a textarea field. They are able to save this information in a database. The problem is that if they have not changed the information or if the information matches the data already in the database, I recieve a '0' for affected rows. Usually I display an error that says the query failed when there are no affected rows. How would I 'know' that the 0 affected rows is because the data already exists, so that I can display a more specific error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
获得 0 条受影响行的另一个原因是
UPDATE
语句没有匹配任何行。例如:如果不存在
id = 1234
的行,则给出 0 个受影响的行。这也不是一个错误,它只是一个碰巧没有匹配任何行的UPDATE
。检测这种情况的方法是使用
SELECT
来验证是否存在这样的行。如果您可以确认该行存在,但UPDATE
表示它影响了 0 行,那么您就知道您尝试更改的值实际上是数据库中已有的行。但区别可能并不重要。如果
mysql_error()
说有一个错误,您可能会报告错误,正如 @BoltClock 所建议的那样。*如果没有错误,您可以向用户报告“无更改”。
Another reason you'd get 0 affected rows is if the
UPDATE
statement matches no rows. For instance:Gives 0 affected rows if no row exists with
id = 1234
. This is not an error either, it's just anUPDATE
that happened to match no rows.The way to detect this case is to use
SELECT
to verify that there is such a row. If you can confirm the row exists, but theUPDATE
said it affected 0 rows, then you know that the values you tried to change were in fact the rows already in the database.But the distinction may not be important. You could report an error if
mysql_error()
says there is one, as @BoltClock suggests.*If there is no error you could just report "no change" to the user.
由于查询成功,MySQL 不应返回任何错误号(如果返回,则为 0)。在这种情况下,您可以检查受影响的行数是否为 0并且返回的错误号是否为 0。
如果您使用 PHP 进行编码,则可以执行以下操作:
Since the query is successful MySQL should not return any error number (if it does it'll be 0). In that case, you can check if the number of affected rows is 0 and the error number returned is 0.
If you're coding in PHP, you can do something like this:
补充一下上面的答案。
To supplement the answer above.