如果使用mysql查询更新行,如何在PHP中返回(How to return in PHP, if row was updated using mysql query)

我使用以下查询/代码片段,通过PHP更新MySQL数据库 -

$sql = "UPDATE test_table SET lastname='ram' where id=1"; $result = mysql_query($sql); echo $result;

问题是,即使没有更新,PHP输出也是1 。 例如,在我的情况下,没有包含id=1行,所以当我在phpmyadmin中运行此查询时,它表示0 rows affected ,而在PHP中使用相同的查询返回1 。

我的问题是 - 如何更新已完成( $result = 1 )或不( $result = 0 )而不使用新的选择查询来检查更改?

I am using following query/piece of code, for updating a MySQL database via PHP -

$sql = "UPDATE test_table SET lastname='ram' where id=1"; $result = mysql_query($sql); echo $result;

the problem with this is, the PHP output is 1 even if there was no updating done. for e.g. in my case, there is no row that contains id=1 so when I run this query in phpmyadmin it says 0 rows affected, while the using the same query in PHP is returning 1.

My question is - how to know, if the update was done ($result = 1) or not ($result = 0) without using a new select query to check the change?

最满意答案

更新成功时, mysql_query返回true (即,无错误地运行,无论它执行或未更新多少行)。 如果您想要实际更新的行数,则需要调用mysql_affected_rows :

$sql = "UPDATE test_table SET lastname='ram' where id=1"; if (mysql_query($sql)) { $result = mysql_affected_rows(); echo $result; }

mysql_query returns true when an update succeeds (i.e., runs without an error, regardless of how many rows it did or did not update). If you want the number of rows you've actually updated, you need to call mysql_affected_rows:

$sql = "UPDATE test_table SET lastname='ram' where id=1"; if (mysql_query($sql)) { $result = mysql_affected_rows(); echo $result; }

更多推荐