如何在 php pdo 语句中捕获确切的 sql 错误

How to catch exact sql error in php pdo statement

我是 pdo 的新手,因为我刚刚从传统的查询方法转向它。以下是我写的并且有效。我现在担心的是,如果 select、insert 或 update 中的任何查询有任何错误,它们都会被那个 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 ......";

    $selectQueryResult1 = $link->prepare($selectQuery1);
    $selectQueryResult1->bindParam(':uname', $userName);
    $selectQueryResult1->execute();
    $n1=$selectQueryResult1->rowCount();
    //echo "TEST : ".$n1;
    if($n1==1)
    {
        $row1 = $selectQueryResult1->fetch();
        $userID=$row1['userID'];

                if($row1['up']==$up){

            $insertQuery1 ="Insert .......... ".                                     
              $insertQueryResult1 = $link->prepare($insertQuery1);
                $insertQueryResult1->bindParam(':uID', $userID);
                $insertQueryResult1->bindParam(':uIP', $userIP);
                if($insertQueryResult1->execute()){


                }
                else{
                    $rollBackStatus="True";
                    $link->rollback();
                }
                $updateQuery1 ="Update ........ ";
                    $updateQueryResult1 = $link->prepare($updateQuery1);
                $updateQueryResult1->bindParam(':uID', $userID);
                if($updateQueryResult1->execute()){


                }
                else{
                    $rollBackStatus="True";
                    $link->rollback();
                }   
        }           

}
catch(PDOException $pe)
{
    $rollBackStatus="True";
    die("Error in selectQuery1 :" . $pe->getMessage());
    $link->rollback();
}
if($rollBackStatus=="False"){
    $link->commit();
    $link=null;
    if($headerSent!="")
    {
        header($headerSent);
    }
}

您可以使用以下方法在执行查询后检查任何错误。

$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);