Check if username exists

Im doing a registration script for my site and I want to check if $ _POST ['username'] exists in db.

Is there a better way to code? I do the same for email.

Here's what 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.');
+3
source share
3 answers

Add unique constraintto table:

alter table users
add unique (username)

Then your instructions insertor updatefail:

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

Of course, the big problem with your code is that you are not 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');
+4
source

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

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

If you set the username as “unique” in your database, you can simply run an insert request that fails (which you can process). The same goes for email - to make it "unique."

This may come in handy.

0
source

Source: https://habr.com/ru/post/1716446/


All Articles