PHP creating username with random number
I don't write PHP, but there are several general things I would suggest.



Your 2-space indent makes your code more difficult to read, I would recommend 4. 



$digits is always 4, so I would declare it as a constant, and rename it accordingly. You can move it outside the while loop also.

const $NUMBER_OF_DIGITS = 4;




$first3 and $last3 are also not going to change, so I would move them out of your while loop, and also name them accordingly.

const $NUMBER_OF_DIGITS = 4;
const $FIRST_3 = substr($firstname, 0, 3);
const $LAST_3 =  substr($lastname, 0, 3); 
while($user == $dbusername) {
    // ...




Your comments point out what should be easy to deduct for anyone who writes code regularly. I would suggest to reserve comments for function/class documentation (for example using PHPDoc) and otherwise, just to document things that are not obvious, or may be unusual workarounds to a certain problem/use case.

I think, in particular, perhaps this line deserves a short explanation:

$randomNumber = rand(pow(10, $digits-1), pow(10, $digits)-1);


Comments can also cause more work for you as the maintainer, as you have to also maintain comments in addition to the code, if anything is changed.

Comments can also be misleading, take this for example:

  // if the created user happens to exist in the database, set it to $dbusername
  $dbusername = $row['username'];   
  // rerun the loop if this happens


The comment should really say something like:

  // set $dbusername to either NULL, or an existing username in the case it does exist, which will cause the loop to re-run if it already exists in the database


But that's already pretty obvious from the code, so I would just delete the comment instead, along with most or all of the other ones.



Lastly, I think the while loop works fine, but a do-while loop would make a bit more sense, in that it makes it clear that the loop should run at least once, but may run more times under certain conditions. 

do {
    // your logic code as it is
} while($user == $dbusername);