0

I have an add post form to add new post. I have taken post title as post_url or slug. I want unique post_url.
Here is what I have done so far -

$post_name = $this->input->post('post_title'); function clean($post_name) { $name = trim($post_name); $post_name = str_replace(' ', '-', $name); return preg_replace('/[^A-Za-z0-9\-]/', '', $post_name); } $post_url = clean($post_name); $query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'"); while ($r = mysql_fetch_assoc($query)) { $slugs[] = $r['post_url']; if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) { $max = 0; while (in_array(($post_url . '-' . ++$max), $slugs)) ; $post_url .= '-' . $max; } } echo "Slug " . $post_url; 

I am getting output as -

post-url

post-url-1

post-url-1-1

post-url-1-1-1

But I want output as -

post-url

post-url-1

post-url-2

post-url-3

What is a problem in my code?
Please help me.
Thanks.

3
  • first change $post_url .= '-' . $max; to $post_url = $post_url. $max; Commented Jan 17, 2017 at 13:28
  • @coder It is just removing hyphen(-) and showing output as post-url, post-url1, post-url2 Commented Jan 17, 2017 at 13:41
  • plz check the ans. Commented Jan 17, 2017 at 13:49

2 Answers 2

3
function UniqueSlugGenerator($p){ include("conn.php"); $RowCou=0; $slug = preg_replace('/[^a-z0-9]/', '-', strtolower(trim(strip_tags($p)))); $qq = mysqli_query($conn,"select Slug from ser_posts where Slug like '$slug%'") or die(mysqli_error($conn)); $RowCou = mysqli_num_rows($qq); return ($RowCou > 0) ? $slug.'-'.(++$RowCou) : $slug; } 
Sign up to request clarification or add additional context in comments.

Comments

2

Change your code in the following way

$post_url = clean($post_name); $post_url1 = $post_url; $query = mysql_query("select post_url from sa_posts where post_url like '" . $post_url . "%'"); while ($r = mysql_fetch_assoc($query)) { $slugs[] = $r['post_url']; if (mysql_num_rows($query) !== 0 && in_array($post_url, $slugs)) { $max = 0; $post_url = $post_url1; while (in_array(($post_url . '-' . ++$max), $slugs)) ; $post_url .= '-' . $max; } } echo "Slug " . $post_url; 

1 Comment

@ coder This is exactly what I wanted. Thanks a lot.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.