开发者

How should I handle the case in which a username is already in use?

To practice PHP and MySQL development, I am attempting to create the user registration system for an online chess game.

What are the best practices for:

  • How I should handle the (likely) possibility that开发者_如何学Go when a user tries to register, the username he has chosen is already in use, particularly when it comes to function return values? Should I make a separate SELECT query before the INSERT query?

  • How to handle varying page titles?

    ($gPageTitle = '...'; require_once 'bgsheader.php'; is rather ugly)

(An excerpt of the code I have written so far is in the history.)


Do a separate SELECT to check whether the username is already in use before attempting to INSERT.

More importantly, I would suggest something like the following structure for the script you're writing. It has a strong separation of presentation logic (e.g. HTML) from your other processing (e.g. validation, database, business logic.) This is one important aspect of the model-view-controller paradigm and is generally considered a best-practice.

<?php

// The default state of the form is incomplete with no errors.
$title = "Registration";
$form_completed = false;
$errors = array();

// If the user is submitting the form ..
if ($_POST) {

    // Validate the input.
    // This includes checking if the username is taken.
    $errors = validate_registration_form($_POST);

    // If there are no errors.
    if (!count($errors)) {

        // Add the user.
        add_user($_POST['username'], $_POST['password']);

        // The user has completed.
        $form_completed = true;

        // Optionally you could redirect to another page here.

    } else {

        // Update the page title.
        $title = "Registration, again!"

    }

}

?>

<html>
<head>
<title>Great Site: <?= $title ?></title>
<body>

<?php if ($form_complete): ?>

    <p>Thanks for registering!</p>

<?php else: ?>

    <?php if (count($errors)): ?>
    <ul>
    <?php foreach ($errors as $error): ?>
    <li><?= $error ?></li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>

    <form method="post">
    Username: <input type="text" name="username">
    Password: <input type="password" name="password">
    <input type="submit">
    </form>

<?php endif; ?>

</body>
</html>


Well, one thing you can do instead of repeating code down near the bottom is this:

if( $result === true ) {
    $gPageTitle = 'Registration successful';
    $response = <p>You have successfully registered as ' . htmlspecialchars( $username ) . ' on this site.</p>';
} elseif( $result == 'exists' ) {
    $gPageTitle = 'Username already taken';
    $response = '<p>Someone is already using the username you have chosen. Please try using another one instead.</p>';
} else {
    trigger_error('This should never happen');
}

require_once 'bgsheader.php';
echo $response;
require_once 'bgsfooter.php';

Also, you can return false rather than the string 'exists' in the function, not that it makes much difference.

Checking the error number isn't bad, I'm sure that's why it's an included feature. If you really wanted to do something different, you could check if there already is a user by that name by selecting the username. If no result exists, then insert the user, otherwise, give the error.

One thing I like to do with error handling on forms is save all the error strings into an array like $error['username'], $error['email'], etc., and then have it run through the error checking on each input individually to set all the error strings, and then have a function that does something like this:

function error($field)
{
     global $error;
     if(isset($error[$field]))
     {
          echo $error[$field];
     }
}

and then call that after each field in the form to give error reporting on the form. Of course, the form page must submit to itself, but you could have all the error checking logic in a separate file and do an include if $_POST['whatever'] is set. If your form is formatted in a table or whatever, you could even do something like echo '<tr><td class="error">' . $error[$field] . '</td></tr>, and automatically insert another row directly below the field to hold the error if there is one.

Also, always remember to filter your inputs, even if it should be filtered automatically. Never pass post info directly into a DB without checking it out. I'd also suggest using the specific superglobal variable for the action, like $_POST rather than $_REQUEST, because $_REQUEST contains $_GET, $_POST, and $_COOKIE variables, and someone could feasibly do something strange like submit to the page with ?username=whatever after the page, and then you have both $_POST['username'] and $_GET['username'], and I'm not sure how $_REQUEST would handle that. Probably would make there be a $_REQUEST['username'][0] and $_REQUEST['username'][1].

Also, a bit about the page titles. Don't know if you have it set up like this but you can do something like this in your header:

$pageTitle = "My Website";
if(isset($gPageTitle))
{
    $pageTitle .= "- $gPageTitle";
}
echo "<title>$pageTitle</title>";

Which would make the page load normally with "My Website" as the title, and append "- Username already exists" or whatever for "My Website - Username already exists" as the title when $gPageTitle is set.


I think the answer from Mr. Neigyl would require a separate trip to the database, which is not a good idea because it would only add performance overhead to yuor app. I am not a PHP guru, but I know my way around it, although I don't recall the === operator. == I remember. You could pass the function call directly into the IF statement.

if (addUser($username, $passwd));

I don't see anything wrong with using the $gPageTitle variable, but you will probably have to declare it "global" first and then use namespaces so you can actually access it within the "header.php" because "header.php" will not know how to address this page's variables. Although I personally don't like messing with namespaces and I would rather call a function from the "header.php" and pass the page title into it

  display_title($pgTitle);

or

  display_title("Registration Successfull");

or

  $header->display_title("Registration Successfull")

if you like OO style better

Let me know if that helps. :)


  1. You should get into forms and allow your page to redirect to another page where you have there the 'insert username to database'.
  2. Suppose the username entered is in a post variable such as $_POST['username'].
  3. Have your database check where that username exist:

    $res = mysql_query("SELECT * FROM table WHERE username='$_POST['username']'") or die(mysql_error());
    if(mysql_num_rows($res) > 0) {
    echo "Username exists.";
    // more code to handle username exist    
    } else {
    // ok here.
    }
    

What is basically done is we check if your table already contains an existing username. mysql_num_rows($res) will return 0 if no username exist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜