Reputation:
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.');
Upvotes: 3
Views: 4222
Reputation: 95203
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');
Upvotes: 4
Reputation: 10670
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.
Upvotes: 0
Reputation: 1095
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.');
Upvotes: 0