PDO交易。什么是回滚的正确方法

时间:2016-09-18 10:25:26

标签: php sql pdo

这不是另一个问题的重复。

我的问题是: 如果我在途中遇到任何错误,我必须如何运行交易并回滚

尝试下一步:如果第一个事务(查询)成功,则转到第二个事务。第二个查询在循环中执行以插入所有选择下载的图像。所以,如果第一次 - 第二次成功的举动。如果第二个故障发生了,我想取消第一个。帮忙解决这个问题,谢谢!如果您需要其他信息,例如我的课程class connectPDO或其他内容,我将添加。

    try{
        $this->_pdo->beginTransaction();

        //first transaction
        $content_query = "INSERT INTO 
           products_content 
          (url, title, content, meta_title, meta_description, meta_keywords)
           VALUES 
          (:url, :title, :content, :meta_title, :meta_description, :meta_keywords)";

            $this->_pdo->prepare($content_query);
            $this->_pdo->bind(':url', $url);
            $this->_pdo->bind(':title', $title);
            $this->_pdo->bind(':content', $content);
            $this->_pdo->bind(':meta_title', $metaTitle);
            $this->_pdo->bind(':meta_description', $metaDescription);
            $this->_pdo->bind(':meta_keywords', $metaKeywords);
            $this->_pdo->execute();
            $last_id = $this->_pdo->lastInsertId();


            $Uploads->setDirectory('products/id_'.$last_id);
            $fileArray = $Uploads->saveFiles($files);

            for($i=0;$i<count($fileArray['full_size']);$i++) {

                    //second++ transaction
                    $file_query = "INSERT INTO products_images 
                     (product_id, full_size, mini_size) 
                    VALUES 
                     (:product_id, :full_size, :mini_size )";

                $this->_pdo->prepare($file_query);
                $this->_pdo->bind(':product_id', $last_id);
                $this->_pdo->bind(':full_size', $fileArray['full_size'][$i]);
                $this->_pdo->bind(':mini_size', $fileArray['mini_size'][$i]);
                $this->_pdo->execute();
            }

            $this->_pdo->commitTransaction();

        } catch (PDOException $e) {
            $this->_pdo->rollBackTransaction();
            return $_SESSION['system']['message'] = "SQL Error: ".$e->getMessage();

        }

0 个答案:

没有答案