Register user account if not already exists?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Register user account if not already exists?

Post 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();
		}
}
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Register user account if not already exists?

Post 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.
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Register user account if not already exists?

Post 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.
Post Reply