使用PDO,如何确保UPDATE语句成功? [英] With PDO, how can I make sure that an UPDATE statement was successful?

查看:133
本文介绍了使用PDO,如何确保UPDATE语句成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎对于INSERT语句,可以使用if (isset($connect->lastInsertId()))来检查INSERT语句是否成功. (如果我错了,请纠正我.)

It seems that for an INSERT statement, one can use if (isset($connect->lastInsertId())) in order to check whether the INSERT statement was successful. (Please correct me if I'm wrong.)

但是对于UPDATE语句,我怎么知道它是否成功?

But for an UPDATE statement, how can I know if it was successful?

例如,我有一个基本的例子,

For example, I have basic one like that:

$statement=$connect->prepare("UPDATE users SET premium='1' WHERE userid=?");
$statement->execute(array($id));

非常感谢.问候

推荐答案

这取决于您所说的成功".如果您的意思是查询执行没有失败,则PDO将在失败时引发异常或从PDOStatement::execute()返回FALSE,具体取决于您设置的错误模式,因此在这种情况下,成功"查询将只是其中execute方法没有返回FALSE或引发异常的情况.

It depends on what you mean by "successful." If you mean that the query executed without failing, then PDO will either throw an exception on failure or return FALSE from PDOStatement::execute(), depending on what error mode you have set, so a "successful" query in that case would just be one in which the execute method did not return FALSE or throw an exception.

如果您说成功"是指实际上已更新了行(相对于仅更新了0行),则需要使用

If you mean "successful" in that there were actually rows updated (versus just 0 rows updated), then you'd need to check that using PDOStatement::rowCount(), which will tell you the number of affected rows from the previous query.

警告:对于newvalue = oldvalue PDOStatement::rowCount()返回零的更新.您可以使用

Warning: For updates where newvalue = oldvalue PDOStatement::rowCount() returns zero. You can use

$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));

以禁用此意外行为.

这篇关于使用PDO,如何确保UPDATE语句成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆