Creating a unique random 5 character slug
Hi I have a function that will generate a random string which works fine. What I would like to do is store that string as the pr开发者_如何学Goimary key in my database. The problem is that I first need to make sure that the string is unique before storing it. Here is what I have so far. I'm sure I need a loop until result = <0 but not sure how to go about that any help would be much appriciated. I'm also open to a better solution as I think this may be a slow solution.
//generate random slug
function genRandomString($length=10,$characters = '0123456789abcdefghijklmnopqrstuvwxyz',$string = '') {
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string; }
//store slug into variable
$slug = genRandomString('5');
//select the slug that is equal to our slug
$qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
$result = mysql_query($qry);
//if reslut make a new slug (this dosen't recheck the new slug which is a problem)
if($result >= 0){
$slug = genRandomString('5');
}
First, instead of $result >= 0
, use mysql_num_rows($result) >= 0)
. Next, you'll likely want to wrap this whole thing in a while:
do{
$slug = genRandomString(5);
//select the slug that is equal to our slug
$qry = "SELECT `slug` FROM `drink_data` WHERE `slug` = '$slug'";
$result = mysql_query($qry);
}while(mysql_num_rows($result) > 0);
This will keep generating new slugs (and checking their uniqueness) until it finds something. You'll probably want to add code to bail on saturation (5 numbers isn't that long, you'll fill up quickly and this loop will run exponentially slower).
精彩评论