Kevin G
Kevin G

Reputation: 119

How to check for repeating records e.g username when entering records into database

I am trying to ensure that a username cant be repeated when entering records to a database..I am getting this error "mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Syokimaufc\register.php " My user id field has been auto increemented and that seems to be the issue. how do i fix this?

<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
    $username = mysql_real_escape_string($_POST['username']);
    $password = md5(mysql_real_escape_string($_POST['password']));
    $email = mysql_real_escape_string($_POST['email']);
    $tel = mysql_real_escape_string($_POST['tel']);
    $address = mysql_real_escape_string($_POST['address']);

     $checkusername = mysql_query("SELECT * FROM membership WHERE Username = '".$username."'");

     if(mysql_num_rows($checkusername) == 1)
     {
        echo "<h1>Error</h1>";
        echo "<p>Sorry, that username is taken. Please go back and try again.</p>";
     }
     else
     {
        $registerquery
 = mysql_query("INSERT INTO membership (username, password, email, tel, address) 
VALUES('".$username."', '".$password."', '".$email."','".$tel."','".$address."')");
        if($registerquery)
        {
            echo "<h1>Success</h1>";
            echo "<p>Your account was successfully created. Please <a href=\"index.php\">click here to login</a>.</p>";
        }
        else
        {
            echo "<h1>Error</h1>";
            echo "<p>Sorry, your registration failed. Please go back and try again.</p>";    
        }       
     }
}
else
{
    ?>

Upvotes: 1

Views: 49

Answers (2)

Nadir Latif
Nadir Latif

Reputation: 3773

In your select query Username should be username. So your query should be SELECT * FROM membership WHERE username = '".$username."'". You should use mysqli instead since mysql functions are no longer supported

Upvotes: 0

Josef Kufner
Josef Kufner

Reputation: 2989

To avoid duplicate user names simply create unique index on the user name column in your database. Then, if you try to insert duplicate user name, the insert query will fail and you can react on the failure. No need to lookup user name in the database before inserting the new one.

And don't use mysql_* functions, use PDO instead. And set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, so you get a nice exception when duplicate user name is detected.

Upvotes: 1

Related Questions