简体   繁体   中英

mysql auto increment and unique field

I am writing the following command in 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>';
}

Here in mysql-db I have made name and email field as unique and id as auto increment, so that no two people have same registration records. The problem is that, if someone uses same username or email, the query fails and else statement is executed. But, it auto-increments the id, without getting records added in db. If someone after that registers successfully, he gets an id not 2 more than the previous one.

How to get auto-incremented just once?

There's no real fix; this is how auto-increment IDs work. IDs are not designed to be "clean", they're designed to fullfill a need to be able to link data together.

It'll be a huge amount of work for your database to keep them in order and (here's the most important part) nobody cares about whether they're aligned anyway. They're numbers without a real-world meaning (by definition of being a database ID) so nothing about them should matter.

The only reason they're "in order" normally is because it's an easy way to generate them.

What you need to do is run an num_rows on it, before you insert it. what num_rows do, it count how many records the SELECT returns, so if it returns 1, there is a place in the database where there are a match, if it returns 0, there are no match

$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>';
    }
}

This is a good way to secure, that the error you're talking about wont happend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM