Page 1 of 1

Register user account if not already exists?

Posted: Wed Apr 11, 2012 1:02 pm
by Sindarin
I am trying to create a function to register an account, but I need to check if the username does not exist already. Can I do it with one query?

Tried this but doesn't work:

Code: Select all

function register($details)
{	
		$query_row = "";
		foreach($details as $key => $value) {
			$query_row .= "`".$key."`,";
		}
		$query_row = rtrim($query_row,',');
		
		$query_values = "";
		foreach($details as $key => $value) {
			$query_values .= "'".$this->db_object->escape($value)."',";
		}
		$query_values = rtrim($query_values,',');
		
		$this->db_object->query("INSERT INTO `".$this->users_table."` (`id`,".$query_row.") VALUES(NULL,".$query_values.") WHERE NOT EXISTS username='".$this->db_object->escape($details['username'])."");
		
		if ($this->db_object->get_error_code()!=0){
			echo 'not registered'; return false;
		} else {
			echo'registered'; return $this->db_object->get_insert_id();
		}
}

Re: Register user account if not already exists?

Posted: Wed Apr 11, 2012 1:05 pm
by Celauran
I don't believe you can use a WHERE clause in an INSERT. If your username field is unique, I suppose you could just try a blind insert and check for errors. Why not use a SELECT COUNT(id)? SELECTs are cheap.

Re: Register user account if not already exists?

Posted: Wed Apr 11, 2012 1:25 pm
by Sindarin
Ah totally forgot about UNIQUE. Made username field unique and added a check when mysql error is 1062 (duplicate entry). That seems it works, thanks.