Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
PHP and MySQL help: Checking to see if a username already exists in a database...?
I am trying to create a registration system with PHP and MySQL. At the moment, I am trying to set it up so that, if a user tries to register with a name that's already in the database, they get a "Sorry, that name's already taken-- try again" message. Otherwise, their information gets added to the database.
The database name is bookmarks. The name of the table is user, and name of the field is username.
How do I query the database to determine if the username already exists?
3 Answers
- 1 decade agoFavorite Answer
//assume that the text field name is txtUsername
$username = $_POST['txtUsername'];
//connect to the server using your hostname, username, and password
mysql_connect($host,$usr,$pwd) or die (mysql_error());
//select the database
mysql_select_db('bookmarks') or die (mysql_error());
//get a result set of the query
$rs = mysql_query("select * from user where username = '$username'");
if(mysql_num_rows($rs) != 0){ // there is a user with that username aready
//echo the error message here
}
- John JLv 61 decade ago
to be efficient and not waste gobs of memory, never query for * on a table, always use column names. Thus your query to check for a user name should be "SELECT userName FROM bookmarks.user WHERE username='$userName'"
If that returns a record, that user name is in use.
- Interested DudeLv 71 decade ago
There is a pretty good article on this at http://www.phpfreaks.com/tutorials/65/0.php
I will not try to paste the code as Yahoo will just chop it up.