gpt4 book ai didi

php - 在字符串后添加一个数字,如果它已经存在

转载 作者:行者123 更新时间:2023-11-29 02:28:38 25 4
gpt4 key购买 nike

我正在编写一个脚本来检查该 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;
}

上面的新代码工作得很好。但它只检查一次。我怎样才能检查它直到它不存在于数据库中?

尝试在 $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;

最佳答案

您的代码可能容易受到 SQL Injection 的攻击.您应该考虑使用 PDOMySQLi相反。

以下是您如何执行此操作的示例:

$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;
}
}

关于php - 在字符串后添加一个数字,如果它已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com