Royden Rego
Royden Rego

Reputation: 132

Checking whether username exists or not code in sql and php

I have written a code to check whether the username exists in the database or not. It seems to return that there is no such username exists even if there's a same username existing.

$conu=mysqli_connect("localhost","db_user","db_pass","db_name");
$result = mysql_query("SELECT 1 FROM member WHERE username = $username");
if ($result && mysql_num_rows($result) > 0) {
$user_err = "<i><span class='error'>Usernme already exists</span></i>";
    $errflag = true;
}
elseif(preg_match("/^[0-9a-zA-Z_]{5,}$/", $username) === 0) {
    $user_err = "<i><span class='error'>Usernme must be bigger than 5 chararacters and can contain only digits, letters and underscore</span></i>";
    $errflag = true;
}

Upvotes: 0

Views: 512

Answers (4)

Sutandiono
Sutandiono

Reputation: 1750

  1. You are using mysqli to connect, but mysql to perform your query.
  2. When you SELECT 1 FROM member WHERE username = $username, the result will always be 1.
  3. You need to put $username in the query in quotes. Something like SELECT username FROM member WHERE username = '$username'.
  4. You forgot to include the part of the code for when there is no such username in your posting.

Upvotes: 0

Vilsol
Vilsol

Reputation: 722

At first, you are trying to return a column that probably doesn't exist: "1"
Second, I hope that you are cleaning the $username or else you are allowing anyone to inject your database.

The correct query is

mysql_query("SELECT * FROM `member` WHERE `username`='$username'");

Upvotes: 0

Tucker
Tucker

Reputation: 7362

Usernames I take it are some sort of varchar? If that is the case, you might want to put its value in quotes:

$result = mysql_query("SELECT `username` FROM `member` WHERE `username` = '".$username."' LIMIT 1;");

your query is subject to sql injections btw.

Upvotes: 0

George Brighton
George Brighton

Reputation: 5151

Try

mysql_query("SELECT username FROM member WHERE username = '$username' LIMIT 1;");

SELECT 1 is not actually using the database; it's always returning 1, hence why your result is always the same regardless of the contents of the member table.

Upvotes: 3

Related Questions