0

我刚刚将我的 SQLi 转换为 PDO。我不是 100% 确定如何准备 PDO 语句以包含ERRORorSUCCESS语句。我在下面包含了我的部分代码:

// 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 完成相同的任务?

4

2 回答 2

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
}
于 2013-06-24T18:59:12.483 回答
-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';
}
于 2013-06-24T19:00:09.373 回答