Skip to main content
This topic has been closed for replies.

1 reply

David_Powers
Inspiring
June 6, 2011

hjohnson2011 wrote:

I have a registration page in JavaScript that is working fine except for the fact that I need it to check username against the database to insure that usernames do not get duplicated in the database. Because it does not check username I come to realize that user’s information is getting mixed up if the username are the same.  I am sure I am not doing this correctly because I have not used JavaScript before….

When asking for help, you stand a much better chance of getting the answers you need if you create a simple test page to illustrate the problem, rather than posting hundreds of lines of code. A test page helps isolate the problem without being distracted by everything else in your complex form.

What's not clear from your description is what the JavaScript is intended to do. Taking a quick look at the code you have posted here, the Insert Record server behavior handles only the username. Yet your form has dozens of fields. Also, the form's action attribute points to user_registration.php. Is this the same page or a different script? If it's a different script, that's what's inserting the values into the database. The Check User Name server behavior is never called. Or is an external JavaScript file taking the values after validation and using an Ajax call to insert them in the database? Again, this would bypass the Check User Name server behavior.

Having said that, the Check User Name server behavior is, to my mind, worse than useless, because it redirects the user to another page, thereby losing all the user input. The simple solution is to add a UNIQUE index to the username column in the database. This prevents a duplicate entry from being inserted. However, you need to customize the Insert Record server behavior to intercept the MySQL error like this:

  // remove the or die() clause

  $Result1 = mysql_query($insertSQL, $rescue);

  // if the username is already in use

  if (!$Result1 && mysql_errno() == 1062) {

      $error = $_POST['username'] . ' is already in use. Choose another.';

  } elseif (mysql_error()) {

      $error = 'Sorry, there is a problem with the database. Try later.';

  } else {

      $insertGoTo = "myprofile.php";

      if (isset($_SERVER['QUERY_STRING'])) {

        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";

        $insertGoTo .= $_SERVER['QUERY_STRING'];

      }

      header(sprintf("Location: %s", $insertGoTo));

  }  // close extra conditional statement

}

You can then redisplay the page if the username is already taken, and use the $_POST array to preserve the user's input in the form.

hjohnson2011
Participant
June 7, 2011

Thank you for your help. I have decided to re-create the page and not use the code that was provided for me.