php 如何检查行是否已更新?

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

How to check if the row has been updated?

phpmysqlpdo

提问by I'll-Be-Back

How to return a boolean if the record has been updated on the database?

如果记录已在数据库上更新,如何返回布尔值?

Example:

例子:

try {
  $SQL = "UPDATE addressbook SET valid = '0' WHERE id = :id";
  $query = $this->db->prepare($SQL);
  $query->bindValue(":id", $id);
  $query->execute();

  //How do I know if record has been updated? 
} catch (PDOException $e) {
  $j['success'] = 'false';
  echo json_encode($j);
  return;
}

回答by CD001

You can use:

您可以使用:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

PDOStatement::rowCount() 返回受相应 PDOStatement 对象执行的最后一个 DELETE、INSERT 或 UPDATE 语句影响的行数。

如果关联 PDOStatement 执行的最后一条 SQL 语句是 SELECT 语句,则某些数据库可能会返回该语句返回的行数。但是,这种行为并不能保证适用于所有数据库,并且不应依赖于可移植应用程序。

PDOStatement::rowCount(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

PDOStatement::rowCount (PHP 5 >= 5.1.0,PECL pdo >= 0.1.0)

To your particular case, returning a boolean:

对于您的特定情况,返回一个布尔值:

return $query->rowCount() ? true : false;

回答by Levi Morrison

If something went wrong but your code was updated in the database, that sounds like a really precarious state to be in. It's probably better to use a transaction and rollback on exception.

如果出现问题但您的代码已在数据库中更新,这听起来像是一种非常不稳定的状态。最好使用事务并在异常时回滚。

Something like (untested):

类似的东西(未经测试):

$this->db->beginTransaction();
try {
       $SQL = "UPDATE addressbook SET valid = '0' WHERE id = :id";
      $query = $this->db->prepare($SQL);
      $query->bindValue(":id", $id);
      $query->execute();

      $this->db->commit();

      return true;

      //How do I know if record has been updated? 
} catch (PDOException $e) {
      $this->db->rollback();
      return false;
}

Also, you probably don't want to mix your JSON in with this code, separate it out and have something outside your class deal with JSON.

此外,您可能不希望将您的 JSON 与此代码混合在一起,将其分离出来并在您的类之外处理 JSON。