【发布时间】:2023-03-06 22:45:01
【问题描述】:
我有一个连接到 MariaDB 数据库的 PHP 程序。
我将名称上传为“数字”,并将值定义为 UNIQUE,因此我不想重复。
但是我想在重复 vlaue 时处理错误:
这是我创建的表:
MariaDB 中的表
create table test(
-> id int NOT NULL AUTO_INCREMENT,
-> name varchar(255) UNIQUE,
-> date DATE NOT NULL,
-> PRIMARY KEY (id)
-> );
这是 PHP 中的脚本:
$host = "localhost";
$db_name = "xxx";
$username = "xxx";
$password = "xxx";
$connection = null;
$dt1=date("Y-m-d");
try{
$connection = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password);
$connection->exec("set names utf8");
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
function saveData($name, $dt1){
global $connection;
$query = "INSERT INTO test(name, date) VALUES( :name, :date )";
$callToDb = $connection->prepare( $query );
$name=htmlspecialchars(strip_tags($name));
//$dt1=htmlspecialchars(strip_tags($dt1));
$callToDb->bindParam(":name", $name);
$callToDb->bindParam(":date", $dt1);
if($callToDb->execute()){
//return '<h3 style="text-align:center;">registration submmited!</h3>';
//if (!$callToDb->execute()) {
// if ($callToDb->errno == 1062) {
// return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
// }
// else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
// }
}
}
if( isset($_POST['submit'])) {
$name = htmlentities($_POST['name']);
$dt1 = htmlentities($_POST['date']);
//then you can use them in a PHP function.
$result = saveData($name, $dt1);
echo $result;
}
else{
echo '<h3 style="text-align:center;">A very detailed error message</h3>';
}
//header("location:javascript://history.go(-1)");
}
if($callToDb->execute()){ 之后的代码部分被注释了,因为它不起作用,但我想在重复 vlaue 时显示一条消息。与正确注册值时相同。
处理重复错误的问题在于这部分,目前我没有在我的代码中使用它,因为它不能正常工作:
if (!$callToDb->execute()) {
if ($callToDb->errno == 1062) {
return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
}
else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
}
}
知道为什么这部分代码不起作用吗?
【问题讨论】: