View Full Version : Check for Unique Username

Jon W
01-06-2008, 07:37 AM
The title say it all. How can I create a script that will check and see in my database to see if there is already a unique Username. I'm doing this for a Register page.

Thanks for you help in advance.

01-06-2008, 07:53 AM
Depending on how your database is setup you would want to create a form and the mysql query would look something like this

$sql=mysql_query("SELECT user_name FROM your_table_here WHERE username='{$_POST['userid']}'");

if($num_rows >1){

echo 'User Id already exists';

here is a tutorial about forms. http://www.tizag.com/phpT/forms.php

It should help you out with the basics of this.

01-06-2008, 06:17 PM
You'll not want to check for $num_rows > 1... this will only return TRUE if the user name exists twice or more in the database. That code will allow a name to be registered twice before disallowing it to be registered again.

All you really need to check is if any rows were returned, since 0 is equivalent to FALSE and everything above equates to TRUE:

$qry = sprintf( 'SELECT `id` FROM `users` WHERE `userName` = \'%s\'', mysql_real_escape_string( $_POST['userName'] ) );
$res = mysql_query( $sql );
$num = mysql_num_rows( $res );

if ( $num )
echo 'This user already exists';