Reputation: 173
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
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
Reputation: 126
First of all:
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