Jump to content

Checking If A Value Already Exists

- - - - -

  • Please log in to reply
3 replies to this topic

#1
hetra

hetra

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 298 posts
  • Location:Australia
  • Programming Language:C, C++, PHP, Python, Delphi/Object Pascal, Assembly
  • Learning:Python, Assembly
Hello all,

I'm making a registration page for my website. I need to check if a username already exists. What SQL syntax and/or function can do this?
Jack
Creator, Owner, Webmaster
Brezerd.net

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
It really depends on how you're storing them, currently.

I usually do something like: SELECT COUNT(*) AS MYCOUNTER FROM USERS WHERE USER_NAME='new name';

0 means it's available, 1 means it isn't.

Other people will do a select * and look to see if records were returned

Some people do an insert and handle the duplicate value if a primary key violation occurs.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
It should be simple as selecting the count, i.e.
SELECT COUNT(username) FROM tbl_users WHERE username = 'John'
If count > 0:
   //User already exists
You could probably use mysql_num_rows without COUNT if you are using PHP if you require more information (i.e. exists, and was registered at a date, rather than just exists already)
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#4
yassinebelkaid

yassinebelkaid

    Newbie

  • Members
  • PipPip
  • 20 posts
You can do something like this : SELECT username FROM tlb_name WHERE username = '".$username."', then use mysql_num_rows($query). then do a condition if the row equals 1, it means the username exists, if not it will continue and store the new username.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users