• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • PDO::commit()

    (PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

    提交一个事务

    说明

    PDO::commit(void): bool

    提交一个事务,数据库连接返回到自动提交模式直到下次调用PDO::beginTransaction()开始一个新的事务为止。

    返回值

    成功时返回TRUE,或者在失败时返回FALSE

    范例

    提交一个基础事务

    <?php
    /* 开始一个事务,关闭自动提交 */
    $dbh->beginTransaction();
    /* 在全有或全无的基础上插入多行记录(要么全部插入,要么全部不插入) */
    $sql = 'INSERT INTO fruit
        (name, colour, calories)
        VALUES (?, ?, ?)';
    $sth = $dbh->prepare($sql);
    foreach ($fruits as $fruit) {
        $sth->execute(array(
            $fruit->name,
            $fruit->colour,
            $fruit->calories,
        ));
    }
    /* 提交更改 */
    $dbh->commit();
    /* 现在数据库连接返回到自动提交模式 */
    ?>
    

    提交一个DDL事务

    <?php
    /*  开始一个事务,关闭自动提交 */
    $dbh->beginTransaction();
    /* Change the database schema */
    $sth = $dbh->exec("DROP TABLE fruit");
    /* 更改数据库架构 */
    $dbh->commit();
    /* 现在数据库连接返回到自动提交模式 */
    ?>
    

    Note:并不是所有数据库都允许使用DDL语句进行事务操作:有些会产生错误,而其他一些(包括MySQL)会在遇到第一个DDL语句后就自动提交事务。

    参见

    • PDO::beginTransaction() 启动一个事务
    • PDO::rollBack() 回滚一个事务
    • 事务和自动提交
    Keep in mind this bug: https://bugs.php.net/bug.php?id=66528
    you could not rely on commit() return value while using MySql
    Note that this will raise the PDOException on error EVEN if the error handling of PDO is set to PDO::ERRMODE_WARNING.