gpt4 book ai didi

php - mysql重复错误处理

转载 作者:行者123 更新时间:2023-11-30 23:48:02 25 4
gpt4 key购买 nike

我正在尝试使用 PHP 从表单中输入数据。当我尝试输入重复数据时,会弹出一条错误消息,例如

这里出了点问题:

INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie@cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "

相反,我想显示一条干净的错误消息。我怎样才能做到这一点。这是我到目前为止编写的代码...

<?php
include_once "dbConnect.php";
$connection=connectDB();

if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","@");

$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);

//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;

$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";

$customer_idcip = $customer_id-1;
echo $customer_idcip;

if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";

$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}

echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";

//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>

最佳答案

error code (number) is 1022 .
你可以例如为此定义一个常量(以便 x 个月后的其他人有机会理解代码),例如

define('ER_DUP_KEY', 1022);

然后做类似的事情

if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}

因为我不知道如何$res =$connection->query($command);有效(而 $connection 是什么,我无法确切地告诉您如何实现 <error code>==ER_DUP_KEY ,可以使用 mysql_errno 。但它似乎以某种方式与 mysql_query($query) 混合在一起,即旧的、已弃用的 mysql_* 扩展和一些自定义类。你可能想先解决这个问题……;-)
http://docs.php.net/manual/en/mysqlinfo.api.choosing.php

关于php - mysql重复错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com