首页 > 解决方案 > 在 PHP 中显示错误消息,而不是在重复条目上显示服务器错误消息

问题描述

我想要它,如果数据库中已经存在“tags_name”,它将在 php 中显示错误而不是fatel错误消息。

if(isset($_POST['NewTag']))
{
    $tags_name= $_POST['tags_name'];

    $stmt = $DBcon->prepare("INSERT INTO category (tags_name) VALUES(:tags_name)");

    $stmt->bindparam(':tags_name', $tags_name);
    if ($stmt->execute()) {
        $successMSG = "Succesfull";
    } else {
        $errMSG = "Entry already exists";
    }
}

我目前收到此错误“致命错误:未捕获的 PDOException:SQLSTATE [23000]:完整性约束违规:1062 键 'tags_name' 的重复条目 'testing' ....”而不是我的 errMSG。

标签: sqlif-statement

解决方案


对存在的错误代码使用 try catch 是 1062:

 $tags_name= $_POST['tags_name'];
 $stmt = $DBcon->prepare("INSERT INTO category (tags_name) VALUES(:tags_name)");
 try {
     $stmt->excute(':tags_name', $tags_name);
    } catch (PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            $messageError = 'Duplicate entry';
        } else {
            throw $e;
        }
  }

推荐阅读