Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

php - With PDO, how can I make sure that an UPDATE statement was successful?

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.)

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));

Thanks a lot in advance. Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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));

in order to disable this unexpected behaviour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...