0

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");
}
}
?> 
JustLift
  • 153
  • 1
  • 7
  • 17
  • 2
    Repeat after me: I will not put my users in jeopardy by having a vulnerable application. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – PeeHaa Apr 05 '14 at 13:36

2 Answers2

3

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.

vanion
  • 126
  • 1
  • 8
-1

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.

MrDevel
  • 166
  • 2
  • 13
  • Error driven development sounds like a wrong approach to me. – PeeHaa Apr 05 '14 at 13:39
  • @MrDevel, username is a Varchar datatype so can it be UNIQUE key? – JustLift Apr 05 '14 at 13:41
  • @PeeHaa I don't think so. In that way he can use the DB features without creating something new. Otherwise he should look for with another query if the username is already stored and this is a wrong approach to me. – MrDevel Apr 05 '14 at 13:45
  • @SandeshMgr, my comment has been deleted, btw you can use a UNIQUE key on a varchar datatype. I don't know why my post has "-1" but I think it can be a good way to resolve the problem – MrDevel Apr 07 '14 at 09:10