You don't show how you're connecting to mysql, but if perchance you're using mysql_pconnect() you should try changing to plain mysql_connect() and see if the problem goes away.
Also, while you're at it, you can simplify what you've got there quite a bit by noting two things:
(1) PHP has built-in functions for moving (renaming) and deleting files, which are much simpler to use than executing the shell to run commands to do it.
(2) There's no need go get the query results into an array, then laboriously assign each array element to a scalar variable so you can build a subsequent query. Instead, either just the array directly to build the query string, or (my personal favorite) use <b>list()</b> to make the original assignment go directly to the scalar variables and bypass the array entirely, e.g.
$result = mysql_query("SELECT username, gender, location, password, location,
email, aim, icq FROM temp WHERE userid=$i");
list($username, $gender, $password, $location, $email, $aim, $icq) =
mysql_fetch_row($result);