在哪里检查INSERT语句的成功或失败?

时间:2017-02-09 09:43:22

标签: php mysql pdo

我有一个带有表单数据的 INSERT 语句,如果成功与否,我必须向用户回复一条消息。

这是我的代码:

DB::get()->beginTransaction();
$this->inTransaction = true;

$queryInsert = "INSERT INTO DB::$buchungenTabelle 
                    (kurs_id, anrede, vorname, nachname, email, 
                     telefon, status, anzahl_teilnehmer) 
                VALUES (?,?,?,?,?,?,?,?)
                ";

$stmt = DB::get()->prepare($queryInsert);

$stmt->execute(array($eventId, $salutation, $firstName, $familyName, 
                     $email, $telephone, 'gebucht', $participant));

DB::get()->commit();
$this->inTransaction = false;

我应该检查execute()还是commit()的返回值? 即使是在开放交易中,execute()的返回值是否可靠?谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

只要无条件地发送成功消息。如果插入失败,原因很可能是服务器故障,并且在这种情况下出现通用错误消息"服务器错误。请稍后再试#34;应该由专用的错误处理程序显示,该处理程序完全独立于您的特定应用程序代码。

此外,根本不需要交易。因此你的代码将是

$queryInsert = "INSERT INTO DB::$buchungenTabelle 
                (kurs_id, anrede, vorname, nachname, email, 
                 telefon, status, anzahl_teilnehmer) 
            VALUES (?,?,?,?,?,?,?,?)";
DB::get()->prepare($queryInsert)->execute(array($eventId, $salutation, $firstName, 
           $familyName, $email, $telephone, 'gebucht', $participant));
echo "Success";