在向数据库输入重复数据时,如何显示不同的错误消息?Php/MySql
我正在尝试,当用户输入某个区域的名称时,如果重复输入同一个区域的名称,屏幕上会显示“it happed a error”,但我不能这样做。在向数据库输入重复数据时,如何显示不同的错误消息?Php/MySql,php,mysql,pdo,Php,Mysql,Pdo,我正在尝试,当用户输入某个区域的名称时,如果重复输入同一个区域的名称,屏幕上会显示“it happed a error”,但我不能这样做。 Region.php: class Region { private $regID; private $regName; private function loadData() { if(isset($_POST["regID"])) { $this-&g
Region.php:
class Region
{
private $regID;
private $regName;
private function loadData()
{
if(isset($_POST["regID"]))
{
$this->setRegID($_POST["regID"]);
}
if(isset($_POST["regName"]))
{
$this->setRegNombre($_POST["regName"]);
}
}
public function addRegion()
{
$this->loadData();
$link = Connection::connect();
$sql = "INSERT INTO regions(regName) VALUES (:regName)";
$stmt = $link->prepare($sql);
$regName = $this->getRegName();
$stmt->bindParam(":regName",$regName,PDO::PARAM_STR);
if($stmt->execute())
{
return true;
}
return false;
}
}
<?php
require "class/Connection.php";
require "class/Region.php";
$objRegion = new Region();
$objRegion->addRegion();
if($objRegion){
?>
<p>Added region</p>
<?php }else{ ?>
<p>An error occurred.</p>
<?php /*if('error code==666'){ //With the error code show this:
<p>There is already a region with that name.</p>
}*/?>
<?php } ?>
AddRegion.php:
class Region
{
private $regID;
private $regName;
private function loadData()
{
if(isset($_POST["regID"]))
{
$this->setRegID($_POST["regID"]);
}
if(isset($_POST["regName"]))
{
$this->setRegNombre($_POST["regName"]);
}
}
public function addRegion()
{
$this->loadData();
$link = Connection::connect();
$sql = "INSERT INTO regions(regName) VALUES (:regName)";
$stmt = $link->prepare($sql);
$regName = $this->getRegName();
$stmt->bindParam(":regName",$regName,PDO::PARAM_STR);
if($stmt->execute())
{
return true;
}
return false;
}
}
<?php
require "class/Connection.php";
require "class/Region.php";
$objRegion = new Region();
$objRegion->addRegion();
if($objRegion){
?>
<p>Added region</p>
<?php }else{ ?>
<p>An error occurred.</p>
<?php /*if('error code==666'){ //With the error code show this:
<p>There is already a region with that name.</p>
}*/?>
<?php } ?>
附加区域
发生了一个错误
但我在屏幕上看到的是:
警告:PDOStatement::execute():SQLSTATE[23000]:完整性约束冲突:第60行C:\xampp\htdocs\test\class\Region.php中的注册表项'regName'的1062重复条目'America'
附加区域
- 如何使错误消息不显示
- 我如何才能做到,若有错误,添加的区域不会出现,但“是否发生错误”会显示在屏幕上
- 我如何从MySQL错误代码中知道错误是否是名称重复
try..catch
块捕获PDOException
try {
$objRegion->addRegion();
} catch (\PDOException $e) {
$existingkey = "Integrity constraint violation: 1062 Duplicate entry";
if (strpos($e->getMessage(), $existingkey) !== FALSE) {
// here goes is your duplicate data error
} else {
throw $e;
}
}
这个例子是值得一读的,它能让你很好地理解如何在PHP中正确使用PDO。为什么要投反对票?我很欣赏这个版本,但为什么要删除我的整个段落呢?我试图指出错误的根本原因,字段可能不需要是唯一的。如果您有不同的意见或认为这是错误的,请添加您的评论。如果他的目的是不允许重复数据,那么他为什么要检查模式?这样更好,我很欣赏您的评论,您可能有一个正确的观点,但我更愿意由我来决定是否删除我的段落。顺便说一句,我完全尊重你的杰作(唯一合适的)PDO教程,我阅读了它并将其作为一个有价值的参考。嘿,谢谢你的回复!是的,其思想是将regName设置为唯一的。我用try/catch解决了我的问题。但是你的链接帮了我很多。问题是,在我的db connection类中,我没有设置PDO::ERRMODE_异常,因此无法捕获异常。谢谢你的帮助!