如果表中已经存在 slug,如何在 slug 之后添加数字(例如... php-slug-1)
如果数据库中已存在相同的slug,如何添加数字
<?php
if ($title == "" || $cat == "" || $body == "" || $author == "" ) {
echo "<span class='error'>Field must not be empty !! </span>";
} else{
$query = "INSERT INTO tbl_post( title, slug, cat, body, tags, author,viewname, userid, userrole) VALUES( '$title', '$slug', '$cat', '$body', '$tags', '$author', '$viewname', '$userid', '$userrole' )";
$inserted_rows = $db->insert($query);
if ($inserted_rows) {
echo "<span class='success'>Post Inserted Successfully.
</span>";
}else {
echo "<span class='error'>Post Not Inserted !</span>";
}
}
}
?>
请帮助解决我的问题。我是php新手
how to add number if same slug already exist in database
<?php
if ($title == "" || $cat == "" || $body == "" || $author == "" ) {
echo "<span class='error'>Field must not be empty !! </span>";
} else{
$query = "INSERT INTO tbl_post( title, slug, cat, body, tags, author,viewname, userid, userrole) VALUES( '$title', '$slug', '$cat', '$body', '$tags', '$author', '$viewname', '$userid', '$userrole' )";
$inserted_rows = $db->insert($query);
if ($inserted_rows) {
echo "<span class='success'>Post Inserted Successfully.
</span>";
}else {
echo "<span class='error'>Post Not Inserted !</span>";
}
}
}
?>
please help about my problem. I am new learner php
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在数据库中使
title
唯一,然后将 slug 基于标题,如下所示:该函数的作用基本上是将每个大写字母替换为小写字母并删除非法字符。例如,
Hello World!
变为hello-world
。由于多个标题具有相同名称的概率很低,并且在数据库列上也具有唯一属性,因此您很可能不会得到任何重复的 slugs。
在我看来,这也是比
hello-world
、hello-world-1
、hello-world-2
等更干净的解决方案查看如何使列在数据库中唯一
Why not make
title
unique in your database and then base the slug on the title, like so:What the function does is basically replacing every uppercase to lowercase and removing illegal chars. For example
Hello World!
becomeshello-world
.Since the probabilty for multiple titles with the same name is low, and also having the unique attribute on the database column, you will most likely not end up with any duplicate slugs.
It is in my opinion also a cleaner solution than to have
hello-world
,hello-world-1
,hello-world-2
, etc.see here how to make a column unique in your database