Use part of user email to create auto username

Hi i am creating a signup page where a user only has to supply a email and password.

I want to then use the first part of the supplied email or should i say anything prior to @ symbol to populate username.

example

email = test@test.com

username = test

which i can do by this code;

$username = substr($email, 0, strpos($email, '@'));

However this would error when a user registers with test@testing.com. Therefor in this instance i would want code to create the username as test1.

I am new to php and would love someone to help me write the code to make sure i submit a unique username. I presume you would use a while statement.

I found this example during a search, how would i translate this to yii;

$username = substr($username, 0, strpos($username, '@'));





$username = mysql_real_escape_string($username);





$result = mysql_query('SELECT `username` FROM `users` WHERE `username` = '' . $username . '%';');





if (mysql_num_rows($result) > 0) {





   $i = 0;





   while ($name_arr = mysql_fetch_assoc($result)) {





      $name = $name_arr['username'];       





      $after = substr($name, strlen($username));





      if (ctype_digit($after)) {





         if (($after = (int) $after) > $i) {





            $i = $after;





         }





      }





   }





   if ($i > 0) {


      $username .= $i;


   }





}

Anyone????

Something like this, without looking at your logic



<?php


    $username = mysql_real_escape_string(substr($emil, 0, strpos($username, '@')));


    $users    = Users::model()->findall ('username LIKE :username', array(':username' =>$username.'%')); 





    if (count($users) > 0) {


       $i = 0;


       foreach ($users as $user) {


          $name  = $user->username;       


          $after = substr($name, strlen($username));


          if (ctype_digit($after)) {


             if (($after = (int) $after) > $i) {


                $i = $after;


             }


          }


       }


        if ($i > 0) {


          $username .= $i;


       }


    }


?>


Why don't you use the whole email address as username, many webapps do that?

Quote

Why don't you use the whole email address as username, many webapps do that?

I am still using the full email address as the username for login etc. but I am wanting to create a profile for the user automatically when sign up occurs and using the email address is too long. User can always change profile name at a later stage