mysql自动递增和唯一字段


mysql auto increment and unique field

我正在php中编写以下命令:

$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password',   '$name', '$email')";
if(mysql_query($query))
{                                       
    header("Location:thislocation.php");
} else {
    echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <a href="forgotmypassword.php" title="Forgot Password?" alt="Forgot Password?"><u><i>click here</i></u></a>.</strong></font><br>';
}

在mysqldb中,我已经将name和email字段设置为唯一的,将id设置为自动递增,这样就不会有两个人有相同的注册记录。问题是,如果有人使用相同的用户名或电子邮件,查询将失败,else语句将被执行。但是,它会自动增加id,而不会在数据库中添加记录。如果之后有人成功注册,他会得到一个不比前一个多2的id。

如何只自动递增一次?

没有真正的修复;这就是自动递增ID的工作方式。ID的设计并不是为了"干净",而是为了满足将数据链接在一起的需要。

要使数据库保持有序,需要做大量的工作,而且(这里是最重要的部分)没有人关心它们是否对齐。它们是没有现实意义的数字(根据数据库ID的定义),所以它们应该无关紧要。

它们正常"有序"的唯一原因是因为这是一种生成它们的简单方法。

您需要做的是在插入它之前在它上运行一个num_rows。num_rrows的作用是计算SELECT返回的记录数量,所以如果它返回1,则数据库中有一个匹配的位置,如果它返回0,则没有匹配的

$selectSql = "SELECT * FROM tableone WHERE name= '".$name."' OR email = '".$email."'";
$result = mysql_query($selectSql, $YOUR_DATABASECONNECTION);
$num_rows = mysql_num_rows($result);
if($num_rows){
echo "email or name is already taken";
}else{    
$query="insert into tableone (user_name, password, name, email) values('$user_name', '$password',   '$name', '$email')";
    if(mysql_query($query))
    {                                       
        header("Location:thislocation.php");
    } else {
        echo '<br><br><font color="red"><strong>Username or EmailId already exists. Please try different Username.<br> If you have forgotten your Password <a href="forgotmypassword.php" title="Forgot Password?" alt="Forgot Password?"><u><i>click here</i></u></a>.</strong></font><br>';
    }
}

这是一个很好的安全方法,这样你所说的错误就不会发生在