PHP PDO错误&成功消息

时间:2013-06-24 18:57:59

标签: php pdo

我最近刚将我的SQLi转换为PDO。我并非100%确定如何准备PDO语句以包含ERRORSUCCESS语句。我在下面列出了部分代码:

// query
$sql = "INSERT INTO data (avatar,citid,birthday,citname,level,experience,rank,rankimage,elite_citizen,points,strength,status,citizenship,mu,date) VALUES (:avatar,:citid,:birthday,:citname,:level,:experience,:rank,:rankimage,:elite_citizen,:points,:strength,:status,:citizenship,:mu,:date)";
$q = $conn->prepare($sql);
$q->execute(array(':avatar'=>$avatar,':citid'=>$citid,':birthday'=>$birthday,':citname'=>$citname,':level'=>$level,':experience'=>$experience,':rank'=>$rank,':rankimage'=>$rankimage,':elite_citizen'=>$elite_citizen,':points'=>$points,':strength'=>$strength,':status'=>$status,':citizenship'=>$citizenship,':mu'=>$mu,':date'=>$date));

在MYSQL中,我发现使用下面的语句更容易:

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}

else {
echo "ERROR";
}

我如何为PDO完成同样的工作?

2 个答案:

答案 0 :(得分:1)

  

我如何为PDO完成同样的工作?

PDO使用例外(默认情况下)。这意味着您可以使用try-catch块来捕获异常(如果发生)并打印错误消息。

如果一切顺利,将跳过错误消息块,如果发生错误,将跳过成功消息并运行catch块。

try {
    // pdo code
    // success message
} catch( PDOException $e ) {
    // error message
}

在您的具体案例中:

try {
    $sql = "...";
    $q = $conn->prepare($sql);
    $q->execute(array(...));
    echo 'Good'; // success message
} catch( PDOException $e ) {
    echo 'Bad'; // error message
}

答案 1 :(得分:-1)

通过检查execute的返回结果:

$sql = "INSERT INTO `data` (`avatar`) VALUES (:avatar)";
$stmt = $conn->prepare($sql);
$res = $stmt->execute(array(':avatar' => $avatar));

if ($res === true) {
    echo 'Success';
}
else {
    echo 'Error';
}