How to know if a MySQL UPDATE query fails because information being supplied matches data already in the database?

前端 未结 2 1247
天涯浪人
天涯浪人 2021-01-19 06:02

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 t

2条回答
  •  伪装坚强ぢ
    2021-01-19 06:34

    Another reason you'd get 0 affected rows is if the UPDATE statement matches no rows. For instance:

    UPDATE MyTable SET field = 'content' WHERE id = 1234;
    

    Gives 0 affected rows if no row exists with id = 1234. This is not an error either, it's just an UPDATE 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 the UPDATE said it affected 0 rows, then you know that the values you tried to change were in fact the rows already in the database.

    SELECT COUNT(*) FROM MyTable WHERE id = 1234;
    

    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.

    * Note: you don't have to report the literal message returned by mysql_error(). The messages can be confusing to users, so it's a good idea to report something more friendly to them.

提交回复
热议问题