sql - 在 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。
解决方案
对存在的错误代码使用 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;
}
}
推荐阅读
- vuejs3 - 如何使用 Composition API 创建带有字典的翻译器
- swift - Swift Combine 共享运算符不起作用?
- c++ - 一个线程写入和另一个读取非原子保证写入
- html - 使用 CSS Grid 的水平 UL
- c# - EF Core Join,同时仅选择连接表
- go - Youtube缩略图上传失败,API
- python - 在 selenium python 中获取多个特定标签
- javascript - 在单个页面中使用多个 jquery ajax 请求的问题
- python - 使用 pandas read.excel 读取单列中的值
- c# - 我们可以在没有 SignalR 的情况下创建 Blazor 服务器应用程序吗?