JustLift
JustLift

Reputation: 173

How to build restriction on user availability during registration using PHP?

I have code that registers users by providing their username, email and password. Now I want to restrict the users to allow only if new username that are not saved into the database. If he/she inputs new username then message should alert notifying that the username you have entered is not available.

The code I have used is below in register.php

<?php       
include"connection.php";          

if (!isset($_POST['submit'])) //if the user clicks the submit button then the PHP code   POST the details 
{
$user_name = $_POST['username']; 
$user_password = $_POST['password']; 
$user_email = $_POST['email']; 

if($user_name && $user_password && $user_email)
    {
        $query = mysql_query("INSERT INTO users (username, password, email, type) 
        VALUES ('$user_name', '$user_password', '$user_email', '0')");
        mysql_query($query); 
echo '<script type="text/javascript">alert("You have been registered");</script>';
}
else {
    echo '<script type="text/javascript">alert("All fields required");</script>'; 
   header("location:user_create.html");
}
}
?> 

Upvotes: 0

Views: 725

Answers (2)

MrDevel
MrDevel

Reputation: 168

Use a UNIQUE key in the db for the username field. Then you can use mysql_error() to catch the error and to show user that he can't use that username because it is already stored in the db.

Upvotes: -1

vanion
vanion

Reputation: 126

First of all:

  • filter data! Users can send unsafe data, so you should use mysql_escape_string() function (it's minimal requirement). Read about SQL Injection and XSS.
  • hash password! Minimal requirement is to use md5 function, read about password hashing: http://www.php.net/manual/en/faq.passwords.php

Use SQL query to check if user login is available:

$result = mysql_query('SELECT * FROM users WHERE username="'.mysql_escape_string($_POST['username']).'"');
if(mysql_fetch_array($result)) {
   // username is unavailable, do something ....
}
else {
  // register user
}

Notice, that mysql function are deprecated from PHP 5.5. Use PDO functions instead.

Upvotes: 3

Related Questions