User id or user email or user mobile number restriction in PHP with unique constraint.
The below is the php script to know the message the user is already registered.
The below is the php script to know the message the user is already registered.
Script for creating the table with UNIQUE userId column
CREATE TABLE test_user (
PK_ID INT NOT NULL AUTO_INCREMENT, userId VARCHAR( 100 ) NOT NULL, password INT( 100 ) NOT NULL, PRIMARY KEY ( PK_ID ), UNIQUE ( userId )
)
PK_ID INT NOT NULL AUTO_INCREMENT, userId VARCHAR( 100 ) NOT NULL, password INT( 100 ) NOT NULL, PRIMARY KEY ( PK_ID ), UNIQUE ( userId )
)
Below is the PHP script to create the user
// to collect the userId and password that posted to page $userId = $_REQUEST['userid']; $password = $_REQUEST['password'];
$query = "INSERT INTO test_user (userId, password) VALUES ('$userId', '$password')"; $result = mysql_query($query);
if(!$result){
if(dbErrorNo() == 1062){ echo 'Sorry, userId already exists.'; } else { // other errors if any echo "Error while creating the user"; } } else {
echo "User created successfully"; }
// function returns the mysql error No function dbErrorNo() {
$query = "INSERT INTO test_user (userId, password) VALUES ('$userId', '$password')"; $result = mysql_query($query);
if(!$result){
if(dbErrorNo() == 1062){ echo 'Sorry, userId already exists.'; } else { // other errors if any echo "Error while creating the user"; } } else {
echo "User created successfully"; }
// function returns the mysql error No function dbErrorNo() {
return mysql_errno();
}
Explanation : mysql_errno function returns the error no. As the userId column is UNIQUE it will return 1062 which is for duplicate entry error
N.B : You need to do your database connection before running the query. You can decode the password before storing for better security.
N.B : You need to do your database connection before running the query. You can decode the password before storing for better security.
0 comments:
Post a Comment