Hi Neil,
you might want to rename your variable that you use for your sql statement as it's the same for your CGI obj. I am talking about "$query". you start with an object then treat it as string for an sql.
to check the username you need to run sql statement with select, something like this will do the job:
select count(*) from members where username = '$username'
if you get one then you have a problem and can go ahead with your error message. also since you do not want to duplicate usernames set this column in table members to be unique.
Hope this helps,
Anton