[PHP] - PDO事务操作

PHP使用PDO事务操作数据库。

参考文章:

http://php.ncong.com/mysql/pdo/pdo_shiwu.html

 

上代码:

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    <?php
       try {
            $pdo = new PDO("mysql:host=localhost;dbname=test", "root", "XXXXXX");
            //设置错误使用异常的模式
            $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            //关闭自动提交
            $pdo-> setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
        } catch (PDOException $e) {
            echo sprintf("Exception message=%s", $e->getMessage());
            exit();
        }
        
        $strSql = "UPDATE mytable SET headline='哈哈' WHERE id=:id";
        
        $pdo->beginTransaction();
        try {
            for ($i = 1; $i <= 5; $i++) {
                $stmt = $pdo->prepare($strSql);
                $affectedRows = $stmt->execute(array("id"=>$i));
                if ($affectedRows > 0) {
                    echo sprintf("update success id=%s<br/>", $i);
                }
                else {
                    echo sprintf("update false id=%s", $i);
                }
            }
            $pdo->commit();
        } catch (PDOException $e) {
            echo sprintf("Exception message=%s", $e->getMessage());
            $pdo->rollBack();
            exit();
        }
        
        // 需要打开自动提交
        $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
        
        echo "<hr/>";
        $stm = $pdo->prepare("SELECT id, headline, create_time FROM mytable");
        $stm->execute();
        $stm->bindColumn(1, $id);
        $stm->bindColumn("headline", $headline);
        $stm->bindColumn(3, $createTime);
        while ($stm->fetch(PDO::FETCH_BOUND)) {
            echo "<p>", $id, " - " , $headline, " - ", $createTime, "</p>";
        }
    ?>
    </body>
</html>

 

posted @ 2015-05-21 17:42  横渡  阅读(646)  评论(0编辑  收藏  举报