On my Articles Site I have ID & Article SLUG setup but I use slug instead of ID. Slug is set as primary unique !
but when user add existing slug again results in die with mysql error Duplicate entry for key 'PRIMARY'
I changed the code to check before insert
$qry="select * from marticles where slug='$slg'";
$res=mysql_query($qry) or die("Error in query!");
$count = mysql_num_rows($res);
if($count > 0) {
echo "Slug Already Exists! Pls change Title/Slug";
}
It now shows Error Message to User Before Insert
But I want to auto rename slug instead of error message e.g. If Previous Slug is "article-on-environment" If user insert same slug again then it will change to "article-on-environment-2" & then next ""article-on-environment-3" so on
I need help in search of same old slug and rename.
You could do the insert and then on mysql_error check the error code and if it is the duplicate key code, change the slug.
$slug='test';
$orig=$slug;
while(!$done) {
$i++;
mysql_query("insert into table set slug = '$slug'");
if(mysql_errno() == 1062) {
$slug=$orig."-$i";
} else {
$done=true;
}
}