James
James

Reputation: 23

How to prevent users from creating an account if username is already taken

I have no idea how to block users from creating account if the username is already taken.. Can someone help me.. I try looking scripts or tutorial on the internet but they're no good.. I'm just a noobie in coding.. my table is called "user_acc" and the username field is "username"

here's my ajax script

function validateEmail(str){ 
    var testresults;

    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    //var filter1=/^[A-Za-z]+$/;
    if (filter.test(str))
        testresults=true;
    else
        testresults=false

    return (testresults)
    }



//registration
$(document).ready(function(){
    $('#submbut').click(function(){

    var fn = $('#fnamae').val();    
    var ln = $('#lnamae').val();
    var un = $('#unamae').val();
    var pass = $('#pass').val();
    var pass2 = $('#pass2').val();
    var mail = $('#mail').val();
    var cont = $('#cont').val();

    var url = "http://localhost/picturecity/acceptusr";

if(fn == "" && ln == "" && un == "" && pass == "" && pass2 == "" && mail == "" && cont == "" || fn == "" || ln == "" || un == "" || pass == "" 
    || pass2 == "" || mail == "" || cont == ""){
 alert('Error: Fill up all fields');
}
else{
     if(pass == pass2)
     {
            if(validateEmail(mail)){
                $.ajax({
                    url:url,
                    data: "fn="+fn+"&ln="+ln+"&un="+un+"&pass="+pass+"&mail="+mail+"&cont="+cont,
                    type:"post",
                    success:function(e){

                        alert('Registration Successful');
                    }//success


                    });//ajax
             }

             else{
                alert("Invalid Email Format");
             }
    }//if

    else{
        alert('Password Do Not Match');
    }
}   







    });//click

}); //document

my controller code for registration

public function acceptusr(){
    $data = array (
            "firstname"=>$this->input->post('fn'),
            "lastname"=>$this->input->post('ln'),
            "username"=>$this->input->post('un'),
            "password"=>md5($this->input->post('pass')),
            "email"=>$this->input->post('mail'),
            "contact"=>$this->input->post('cont')

        );

    $this->Mod_admin->addtotb('user_acc',$data); 
}

the model

public function addtotb($table, $data)
{
    $this->db->insert($table,$data);
}

please help me how to create username validation thanks..

Upvotes: 0

Views: 421

Answers (5)

shiv mint
shiv mint

Reputation: 56

very simple set mysql column where user name stored as unique.

ALTER TABLE tbl_name
  ADD UNIQUE (usr_name);

insert query as

$q= mysqli_query($conn,"insert into users values ('xx', 'xx', 'xx')");
if(!$q){
$error= mysqli_error($q);
//or $error="user name already exits "
header("location:login.php?error=$error");
}

Upvotes: 1

Hemant Maurya
Hemant Maurya

Reputation: 55

/* $username is the desired username from New user that was input field and
you can use mysqli too just by chaging my sql to mysqli   all the best  */

$result = mysql_query("SELECT * FROM users WHERE username='$username'");
if(empty($username) or empty($password1) or empty($password2))
{
    echo '<p>Fields Empty !</p>';
}
elseif(mysql_num_rows($result) == 1)
{
    echo "User exist";
}
elseif($password1 == $password2)
{
    $password = md5($password1);
    mysql_query("INSERT INTO users (username, password) VALUES('$username', '$password')");
    echo "<p>Successfull Register</p>";
}
else
{
    echo 'Password Not Matched';
}

Upvotes: 0

powtac
powtac

Reputation: 41070

The best solution is to make the DB table row "username" unique.

Upvotes: 1

Romeo
Romeo

Reputation: 531

Before $this->db->insert($table,$data); add:

$userq = $this->db->query("SELECT * FROM user_acc WHERE username LIKE '".$data['username']."'");
if($userq->num_rows() == 0)

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

You just need to do a simple validation. If you are using AJAX, you need to perform these steps.

  1. Send the username to the server.
  2. Check for the existence of the username in the Database.
  3. Respond to the client with true or false depending on the presence of the username.
  4. Based on the response, send the user a client side alert!

So to do that, you need to verify it from the server. What you are doing in your question you have posted is just a validation of Email address. Assuming you are familiar with jQuery's AJAX functions, you need to do the following:

  1. Send the username to the server.

    $.get("checkuser.php", {username: $("#username").val()}, function (response) {
    });
    
  2. Check for the existence of the username in the Database.

    $db->query("SELECT * FROM `users` WHERE `username`=" . $_GET["username"]);
    
  3. Respond to the client with true or false depending on the presence of the username.

    if ($db->rowCount() == 1)
      die ("true");
    else
      die ("false");
    
  4. Based on the response, send the user a client side alert!

    $.get("checkuser.php", {username: $("#username").val()}, function (response) {
      if (response == "true")
      {
        alert("User already exists!");
        return false;
      }
    });
    

Upvotes: 2

Related Questions