0

I have slugs formatted like my-cool-slug however I need to auto increment some to make a similar slug unique such as my-cool-slug-2 -3, -4 etc. I am following this post https://stackoverflow.com/a/15972027/635027 to do this but I ran into an issue.

The slug stops at a -1 count when inserting into MySQL and keeps entering that over an over instead of increment to the next integer when finding a duplicate. Below is my query and associated lines. What am I doing wrong?

$slug = 'my-cool-slug';

$slug_query = "SELECT * FROM pv_events WHERE event_slug LIKE '".$slug."%'";
$slug_result = mysqli_query($conn,$slug_query);
$slugs = mysqli_fetch_array($slug_result,MYSQLI_ASSOC);


    if(mysqli_num_rows($slug_result) !== 0 && in_array($slug, $slugs)){
        $max = 0;

        //keep incrementing $max until a space is found
        while(in_array( ($slug . '-' . ++$max ), $slugs) );

        //update $slug with the appendage
        $slug .= '-' . $max;
    }
Community
  • 1
  • 1
RonnieT
  • 2,193
  • 4
  • 32
  • 43
  • The while statement is correct, so the issue is coming from the `mysqli_fetch_array` is it returning the results you're expecting? – Bankzilla May 21 '15 at 02:11
  • No, as Devon mentions below, it is only returning the first result using `mysqli_fetch_array` – RonnieT May 21 '15 at 02:29
  • i assume your events table has an `id` field. why not just append the `id` to the slug and be done with unnecessary shenanigans. – pala_ May 21 '15 at 04:41
  • @pala_ Great idea- thanks. I think you're right that I don't need to over complicate this. Just search the DB for common slug, if exists then it appends the row id. Works great. – RonnieT May 21 '15 at 13:53

2 Answers2

1

mysqli_fetch_array selects the next row, not the entire result set, so $slugs would only contain the first result.

Secondly, if you want to start with 2, it would make sense to set $max to 1, not 0. The first iteration of your while, 1 will be added.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • So I should be using a while and placing results into an array? ` while($row = $slug_result->fetch_array()) { $slugs[] = $row; }` – RonnieT May 21 '15 at 02:25
  • Well I would be doing this differently to begin with. There are various ways that this can be done. – Devon Bessemer May 21 '15 at 14:05
0
  1. Just select "event_slug" instead "*"

    $slug_query = "SELECT event_slug FROM pv_events WHERE event_slug LIKE '".$slug."%'";

  2. Use mysqli_fetch_all

    $slugs = mysqli_fetch_all($slug_result,MYSQLI_ASSOC);

Community
  • 1
  • 1
Nguyễn Nhân
  • 191
  • 1
  • 9