mysql pdo是否需要链接回滚?

时间:2015-07-03 16:00:23

标签: php mysql pdo

我正在将代码移动到使用pdo,因为它更安全,具有sql注入保护功能。我想确认下面的代码可以接受。是$ link-> rollback();放在正确的地方,还是应该在else部分的每个查询后放置?另一个挑战,为什么每当查询出现任何错误时,它只显示最终的catch错误消息而不是在有错误的查询中?

try {
         $dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
        $link = new PDO($dsn, dbUser, dbPassword );
        $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $pe) {
        die("Could not connect to the database $dbname :" . $pe->getMessage());
    }
    $link->beginTransaction();
    $rollBackStatus="False";
    try{

        $selectQuery1 ="Select t*********!=:tn"; 
        $selectQueryResult1 = $link->prepare($selectQuery1);
        $selectQueryResult1->bindParam(':tn', $tn);
        $selectQueryResult1->execute();
        $n1=$selectQueryResult1->rowCount();

        if($n1>0)
        {
            echo "TN ".$tn." Already Exist.</span>";
            $rollBackStatus="True";
        }

        $insertQuery2a =  "Insert Into tblTit Set ". 
                           "tID=:ID, ".
                           "fieldName='tn',".
                            "userID=:uID, ".
                            "dateTimeInsert=now() ";

            $insertQueryResult2a = $link->prepare($insertQuery2a);
            $insertQueryResult2a->bindParam(':ID', $ID);
            $insertQueryResult2a->bindParam(':uID', $_SESSION['userID']);

                if($insertQueryResult2a->execute()){

                }
                else{
                     echo "Error Adding Audit tn: " . $insertQueryResult2a->errorInfo() . "</span>";
                     $rollBackStatus="True";    
                }
               if($rollBackStatus=="False"){

                  $link->commit();  
               }
    }
    catch(PDOException $pe)
    {
        $rollBackStatus="True";
        die("Error in update catch :" . $pe->getMessage());
        $link->rollback();
    }
    $link=null;

0 个答案:

没有答案