The best way to check the existing user in the mySQL database?

advertisements

I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:

function createUser($uname,$pword) {
        $server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
        $this->users = $server->query("SELECT * FROM user_list");
        while ($check = mysql_fetch_array($this->users) {
            if ($check['uname'] == $uname) {

What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):

$boolean = true;
}
if ($boolean) {
    echo "User already exists!";
    }
else {
    $server->query("INSERT USER INTO TABLE");
    echo "User added Successfully";
    }

But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.


Use the WHERE clause to get only rows with the given user name:

"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"

Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:

function createUser($uname,$pword) {
    $server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
    $result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
    if ($result->num_rows() === 0) {
        if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
            echo "User added Successfully";
        } else {
            echo "Error while adding user!";
        }
    } else {
        echo "User already exists!";
    }
}