【发布时间】:2015-12-19 15:56:25
【问题描述】:
我正在开发一个小型 CMS 系统。目前在尝试生成唯一网址时脑死亡。我从页面标题生成 url。有一个很好的脚本来实现这一点,但我无法解决重复的问题。
类似问题here,但得到了准确的输出。
我设法做到以下几点;
this-is-the-slug
this-is-the-slug-2
但如果我第三次创建相同的帖子,它只会重复:this-is-the-slug-2
$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}
我无法绕过它,非常感谢您的帮助。
if(isset($_POST['save'])) {
$title = mysqli_real_escape_string($db, $_POST['title']);
$url = toAscii($title);
// check url
$content = $_POST['content'];
$author = $_SESSION['thelab_username'];
$type = $_POST['type'];
$showtitle = $_POST['showtitle'];
$saveas = $_POST['status'];
$insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");
if($insert === TRUE) {
echo '<div id="success">Page added. <button id="close">Close</button></div>';
}
else {
echo '<div id="error">Failed. Try again. <button id="failed">Close</button></div>';
printf("Errormessage: %s\n", $db->error);
}
}
function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
【问题讨论】:
-
匹配缺少 $ 只是一个错字吗?
-
另外,您应该执行类似 while([此 url 存在于数据库中]){ $url = $baseurl."-".$i++;} 的操作。即使这很危险,如果 $i 失控,您也应该有一些触发的东西;
-
@Jim_M 只是用“匹配”进行演示。
-
@Devrim $connection 是这个 PDO 连接吗?
-
@OlegSamorai 不,它是一个 mysqli 连接。