Two problems: one technical, one conceptual.
The technical problem is that you're only selecting characters from $pattern between the 0th and the 35th inclusive, without
considering how many characters $pattern actually has. So the pattern strings in your switch statement might as well be
1234567890abcdefghijklmnopqrstuvwxyz
AABBCCDDEEFFGGHHIIJJKLMONPQRSTUVWXYZ
aabbccddeeffgghhiijjklmnopqrstuvwxyz
ABCDEFGHIJLNPRTVXZabcdefghijkmoqsuwy
000111122223333444455556666777888999
Where I've sorted the characters so that you can see how some are more likely to appear than others (in lower case strings, 'f' is twice as likely to appear as 'o', for example).
That part of the problem can be fixed by replacing "35" with the length of the pattern (minus 1). Note that some of the calls to mt_rand() have '1' as the lower bound, meaning the 0th character would have no chance of being selected.
The conceptual problem is that you're trying to get this function to do everything. Not only is it generating a random string AND using it (itself a dodgy-sounding idea), but tries to anticipate every possible use of it as well: ASSUMING you have a specific database schema; ASSUMING you're only ever going to use this with MySQL; ASSUMING you want the function to kill the script if the query fails; and ASSUMING that you're only interested in user or record IDs (why not simply use sequential integers?), then any function behaviour other than the default "return the string" may be useful. That's a lot of assumptions. Any time any of those things changes you'll either have to change this function as well, or write it again elsewhere, or use its default behaviour. The last case can be used anywhere: you can leave the user ID and record ID "uses" where they should be - in your code for managing users and records.
Functions shouldn't have to be told what they're being used for. In Soviet Russia, functions use YOU!
So I just figured I'd whip up a cheap-n-nasty random string generator just as an illustration of a function that just generates random strings. To make it a bit more interesting I threw in some switches
to allow different mixes of characters. This code has never been run, let alone tested.
function random_string($length=5, $use_lower=true, $use_upper=true, $use_digit=true, $use_punct=false)
{
if($length<=0)
{
trigger_error('Invalid length for random string', E_USER_WARNING);
return false;
}
$chars = '';
if($use_lower) $chars .= 'qwertyuioplkjhgfdsazxcvbnm';
if($use_upper) $chars .= 'QAZXSWEDCVFRTGBNHYUJMKIOLP';
if($use_digit) $chars .= '0147896325';
if($use_punct) $chars .= '!@#$%^&*=+?';
if($chars == '')
{
trigger_error('No character ranges to generate string from', E_USER_WARNING);
return false;
}
$string = '';
$maxchar = strlen($chars)-1;
for($i=0; $i<$length; $i++)
{
$string .= $chars[mt_rand(0,$maxchar)];
}
return $string;
}