php 成功的 MySQL DELETE 返回什么?如何检查 DELETE 是否成功?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/922398/
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
What does a successful MySQL DELETE return? How to check if DELETE was successful?
提问by jergason
Using PHP, I am trying to delete a record, but I want to check if it was successful or not. Is anything returned from a successful DELETE FROM foo where bar = 'stuff'?
使用 PHP,我试图删除一条记录,但我想检查它是否成功。成功后有什么返回DELETE FROM foo where bar = 'stuff'吗?
Alternatively, do you know any other ways to check if a DELETE was successful? Or am I better off just making sure the row exists before I delete it? I am trying to avoid another query if possible.
或者,您知道检查 DELETE 是否成功的任何其他方法吗?或者我最好在删除它之前确保该行存在?如果可能,我试图避免另一个查询。
回答by Paolo Bergantino
Assuming you are using mysql_query:
假设您正在使用mysql_query:
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
对于其他类型的 SQL 语句,INSERT、UPDATE、DELETE、DROP 等,mysql_query() 在成功时返回 TRUE,在错误时返回 FALSE。
If you are using PDO::exec, then the manual says this:
如果您使用的是PDO::exec,则手册上说:
PDO::exec() returns the number of rows that were modified or deleted by the SQL statement you issued. If no rows were affected, PDO::exec() returns 0.
PDO::exec() 返回由您发出的 SQL 语句修改或删除的行数。如果没有行受到影响,PDO::exec() 返回 0。
Don't want to answer snipe, but since this was selected as the answer, I should note that mysql_query will return TRUEeven if the query did not actually remove anything. You should use mysql_affected_rowsto check for that.
不想回答 snipe,但由于这被选为答案,我应该注意,TRUE即使查询实际上没有删除任何内容,mysql_query 也会返回。你应该用它mysql_affected_rows来检查。
回答by biggusjimmus
Additionally, if you care about the number of rows that were affected:
此外,如果您关心受影响的行数:
[Use] mysql_affected_rows()to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
[使用] mysql_affected_rows()找出有多少行受到 DELETE、INSERT、REPLACE 或 UPDATE 语句的影响。
回答by ryan
you could try this for your php code, placed after your query runs:
您可以为您的 php 代码尝试这个,放置在您的查询运行之后:
if (mysql_affected_rows() > 0) {
echo "You have successfully updated your data.<br><br>";
}
else {
echo "The data you submitted matched the current data so nothing was changed.<br><br>";
}
回答by jedbonheur
For other types of SQLstatements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()returns TRUEon success or FALSEon error.
对于其他类型的SQL语句,INSERT,UPDATE,DELETE,DROP,等mysql_query()返回TRUE成功或FALSE的错误。

