checkuser.php

To go with signup.php, Example 21-6 presents checkuser.php, the program that looks up a username in the database and returns a string indicating whether or not it has already been taken.

Because it relies on the functions sanitizeString and queryMysql, the program first includes the file functions.php. Then, if the $_POST variable 'user' has a value, the function looks it up in the database and, depending on whether it already exists as a username, outputs either “Sorry, this username is taken” or “This username is available.” Just checking the function mysql_num_rows against the result is sufficient for this, as it will return 0 if it is not found, or 1 if it is.

The HTML entities ✘ and ✔ are also used to preface the string with either a cross or a check mark.

Example 21-6. checkuser.php
<?php // checkuser.php
include_once 'functions.php';

if (isset($_POST['user']))
{
    $user = sanitizeString($_POST['user']);

    if (mysql_num_rows(queryMysql("SELECT * FROM members
        WHERE user='$user'")))
        echo  "<span class='taken'>&nbsp;&#x2718; " .
              "Sorry, this username is taken</span>";
    else echo "<span class='available'>&nbsp;&#x2714; ".
              "This username is available</span>";
}
?>