php 如何判断 MySQL UPDATE 何时成功与实际更新的数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7368225/
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-26 02:33:55  来源:igfitidea点击:

How do I tell when a MySQL UPDATE was successful versus actually updated data?

phpmysqlcodeignitersql-update

提问by zechdc

How do I tell when a MySQL UPDATE was successful versus actually updated data?

如何判断 MySQL UPDATE 何时成功与实际更新的数据?

Example:

例子:

TABLE
id    city_name
1     Union
2     Marthasville

If I run the following:

如果我运行以下命令:

$data = array('city_name', 'Marthasville');

//update record 2 from Marthasville to the same thing, Marthasville. 
$this->db->where('id', 2);
$this->db->update('table', $data);

if($this->db->affected_rows() > 0)
{
    //I need it to return TRUE when the MySQL was successful even if nothing was actually updated.
    return TRUE;
}else{
    return FALSE;
}

This will return TRUEevery time the UPDATE statement is successful, but FALSE when no rows were actually updated.

这将在TRUE每次 UPDATE 语句成功时返回,但在没有实际更新行时返回FALSE。

I need it to return TRUEevery time the UPDATE statement was successfully executed even if it doesn't actually change any records.

TRUE每次成功执行 UPDATE 语句时我都需要它返回,即使它实际上没有更改任何记录。

回答by 472084

Have a look at mysql_affected_rows()

看看mysql_affected_rows()

It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.

它应该告诉您是否实际更新了任何内容,而不是没有成功更新导致返回 true。

php.net says:

php.net 说:

mysql_affected_rows()

Returns the number of affected rows on success, and -1 if the last query failed.

mysql_affected_rows()

成功时返回受影响的行数,如果最后一次查询失败,则返回 -1。

You could use the following to achieve your desired results:

您可以使用以下方法来实现您想要的结果:

if($this->db->affected_rows() >= 0){ }

回答by lnguyen55

Then you would use mysql_query:

然后你会使用mysql_query

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。

Simple like this:

简单像这样:

$result = $this->db->update('table', $data);

if($result)
{
     //without error even no row updated
} else {

}