我正在编写一个脚本来检查数据库中是否已存在url,如果是,则在末尾添加额外的-1或-2等等。我找到了this脚本
但是在添加-1之后需要再次检查它。因为它可能已经存在。我怎样才能做到这一点?我这样累了
$query = mysql_query("SELECT * FROM posts WHERE url='$url'");
while ( $query ) {
$result = mysql_fetch_assoc($query);
$url = $result['url'];
$urlnew = $result['url'];
$oldurl = $url;
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
$url = preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $url.$separator.$first;
$first++;
}
$url = $urlnew;
}
上面的新代码运行得很好。但它只检查一次。我怎样才能检查它直到它在DB中不存在?
尝试在$ url - $ urlnew之后在底部添加一个新的SQL查询,但它只会破坏该功能。
修改
这是正确的脚本:D
$query = mysql_query("SELECT * FROM posts WHERE url LIKE '%".$url."%'");
if ( $query ) {
while ( $result = mysql_fetch_assoc($query) ) {
$url = $result['url'];
$urlnew = $result['url'];
$first = 1;
$separator = '-';
while ( $urlnew == $url ) {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $urlnew, $match);
$urlnew = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$url.$separator.$first;
$first++;
}
}
}
$url = $urlnew;
答案 0 :(得分:2)
您的代码可能容易受SQL Injection攻击。您应该考虑使用PDO或MySQLi代替。
以下是您可以这样做的示例:
$url = 'www.example.com';
$i = 0;
$max_duplicates = 100;
$query = $pdo->prepare('SELECT COUNT(id) count FROM urls WHERE url=?');
while ($i++ < $max_duplicates) {
$result = $query->execute($url);
if (!$result->fetch(PDO::FETCH_OBJ)->count)
break;
if ($i == 1) {
$url = $url . '-1';
} else {
$n = $i > 10 ? 2 : 1;
$url = substr($url, -$n) . $i;
}
}
答案 1 :(得分:0)
以下是我用于满足需求的内容
function checkLink($link, $counter=1){
global $connect;
$newLink = $link;
do{
$checkLink = mysqli_query($connect, "SELECT id FROM table WHERE link = '$newLink'");
if(mysqli_num_rows($checkLink) > 0){
$newLink = $link.'-'.$counter;
$counter++;
} else {
break;
}
} while(1);
return $newLink;
}
$link = 'www.example.com';
$uniquelink = checkLink($link);