Check MySQL DB for incremental matches until an unused value is found.. Stumped!

Discussion in 'PHP' started by Chuckun, Sep 6, 2011.

  1. #1
    Hey guys.. I'm creating a CMS at the moment using only unique slugs, no page/post id's in the URL..

    It's 5:28am, my mind is all fuzzy, and I'm getting nowhere racking my brains for the looping solution to my problem..

    I need to check the current slug of a new post against the mysql database to check if it exists or not. This part is easy, obviously..

    If the unique slug is already being used by a different post, I want to append "2 to the end of the slug. If THAT slug is already taken, I need to increase it to "3", and if that's taken, then increase it to "4", etc..

    Example: the slug generated for the new post "My Blog Post" is my-blog-post ... If this slug is already in use by a previous blog post, then I want the slug to be my-blog-post-2, then I want this checked too, and if it exists in the DB already, like the first one, then it should become my-blog-post-3, etc etc..

    I'm sure you'll understand what I'm looking for by this point.. I was a loop to cycle through using $n++ or something just to ensure slugs are checked before being inserted, to keep them unique (the slug field is a unique index but still, I want it to be automatically smoothed over rather than produce an error).

    Thanks for your help, I'm too tired to do this lol..
    Chuckun

    EDIT: Just to make things easier, table = `posts` and slug field = `slug`
     
    Last edited: Sep 6, 2011
    Chuckun, Sep 6, 2011 IP
  2. Chuckun

    Chuckun Well-Known Member

    Messages:
    1,161
    Likes Received:
    60
    Best Answers:
    2
    Trophy Points:
    150
    #2
    Nevermind, my brain finally started working. Ended up with the following.. Seems to work fine. xD I feel stupid now.

    $slug = "blog-post";
    if(mysql_result(mysql_query("SELECT COUNT(*) as Num FROM `posts` WHERE `slug` = '".$slug."'"),0)) {
    	$i=1;
    	$status = "taken";
    	while($status == "taken") {
    		$i++;
    		$newslug = $slug . "-" . $i;
    		if(!mysql_result(mysql_query("SELECT COUNT(*) as Num FROM `posts` WHERE `slug` = '".$newslug."'"),0)) {
    			$status = "available";
    		} else {
    			$status = "taken";
    		}
    	}
    }
    
    PHP:
     
    Chuckun, Sep 6, 2011 IP