简体   繁体   中英

PHP PDO Error & Success messages

I just recently converted my SQLi to PDO. I am not 100% certain how to prepare a PDO statement to include an ERROR or SUCCESS statement. I have included part of my code below:

// 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));

In MYSQL, I found it easier to use the statement below:

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

else {
echo "ERROR";
}

How would i accomplish the same for PDO?

How would I accomplish the same for PDO?

PDO uses exceptions ( by default ). Which means you can use a try-catch block to catch the exception if it occurs and print an error message.

In case everything goes well, the error message block will be skipped, in case an error occurs the success message will be skipped and the catch block will be run.

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

In your specific case:

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

By checking the return result of 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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM