tags:

views:

427

answers:

3

Im making a registration script for my site and i want to check if $_POST['username'] does already exist in db.

Is there a better, less code way of doing it? I do the same for email.

This is how it looks like now:

$checkusername = mysql_query("SELECT username FROM users WHERE username = '$_POST[username]'");
$row83 = mysql_fetch_assoc($checkusername);

if ($_POST['username'] == $row83['username']) die('Username already in use.');
A: 

since you are already checking the username in the sql call, then you really just need to see if a record is returned in the php side of things

$row83 = mysql_query($checkusername);
if (mysql_num_rows($row83) == 0) die('Username already in use.');
mschmidt42
A: 

If you set username as "unique" in your database you can just go ahead and run the insert query, which will fail (which you can handle). The same goes for email - make it "unique".

This may come in handy.

Matthew Iselin
+2  A: 

Add a unique constraint onto your table:

alter table users
add unique (username)

Then, your insert or update statements will fail out:

mysql_query("insert into users (username) values ('$username')")
   or die('Username exists');

Of course, a bigger issue with your code is that you aren't preventing SQL injection. Your code should be:

$username = mysql_real_escape_string($_POST['username']);
mysql_query("insert into users (username) values ('$username')")
   or die('Username exists');
Eric
cool didnt know that thanks mate