Jump to content
Larry Ullman's Book Forums

Databases - How To Tell If A User Does Not Exist


Recommended Posts

I am using what I have learned from the Intro to Databases chapter of the book to create a table that will hold user credentials:

id, firstname, lastname, username, email, hash, timestamp

are the columns.

For the registration page, I want the user to submit the data firstname, lastname, username, email, and the password which will become hash. (hash being the md5($_POST['password']) string).

More to the point, I want a mechanism to check whether or not the user's desired username is already taken or not.

I initally went to page 361 (Retrieving Data from a Database). I found this code, thinking I could use it as a solution:

SELECT * FROM users WHERE name='Larry'

I figure that I can alter it to read:

SELECT * FROM credentials WHERE username="{$_POST['username']}"

(credentials being the table containing the relevant data).

That code would of course be stored in a $query variable.

Would I have to place the code in a loop? I do not think I would have to, since there could only be one username in the table that could match the desired username.

How would I go about checking whether the query (or loop) returned results or not?

Are there any things I can do to make my current system better?

Thank you in advance,

Lingolatz

Link to comment
Share on other sites

You could check that the number of rows returned is equal to 1. Using a limit clause would make the query stop after 1 row was found so saving time searching through the whole table once a match was found.

$q ="SELECT * FROM credentials WHERE username={$_POST['username']} LIMIT 1";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1) {
echo '<p class="error">Username already exists, please choose another.</p>';
}

  • Upvote 1
Link to comment
Share on other sites

Thank you for the tip, margaux.

Here is what I came up with before coming back to check the thread:

if ( empty($_POST['username']) )
{
	$problem = TRUE;
	print '<p>Please enter a username.</p>';
}
{
	include('../mysql_connect.php');
	$query = "SELECT * FROM credentials WHERE username='{$_POST['username']}'";
	$result = mysql_query($query, $dbc);
	if ( !empty($result) )
	{
		$row = mysql_fetch_array($result);
		$problem = TRUE;
		print '<p>Sorry, but the username ' . $_POST['username'] . ' is already in use.</p>';
	}
	else
	{
	  // Username is free!
	}
	mysql_close($dbc);
}

This bit is in between the other checks that I go through (firstname, lastname, etc.) before creating the registration query

Link to comment
Share on other sites

 Share

×
×
  • Create New...