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.
<?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'> ✘ " . "Sorry, this username is taken</span>"; else echo "<span class='available'> ✔ ". "This username is available</span>"; } ?>
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.