gpt4 book ai didi

php - 创建独特的页面标题 slugs php

转载 作者:可可西里 更新时间:2023-11-01 06:34:16 27 4
gpt4 key购买 nike

我有一个为页面标题创建独特的 slug 的功能。它检查 slug 是否在页面表中可用,然后通过相应地添加“-int”来创建一个唯一的 slug。该函数对前三个条目工作正常,例如,输入三次“test slug”将创建“test-slug-1”、“test-slug-2”和“test-slug-3”。然后我收到第四个条目的错误“ fatal error :超过 30 秒的最大执行时间”。逻辑上应该有问题,谁能帮我找出来。下面是代码:

function createSlug($title, $table_name, $field_name) {

global $db_connect;

$slug = preg_replace("/-$/","",preg_replace('/[^a-z0-9]+/i', "-", strtolower($title)));

$counter = 1;

do{

$query = "SELECT * FROM $table_name WHERE $field_name = '".$slug."'";
$result = mysqli_query($db_connect, $query) or die(mysqli_error($db_connect));


if(mysqli_num_rows($result) > 0){
$count = strrchr($slug , "-");
$count = str_replace("-", "", $count);
if($count > 0){

$length = count($count) + 1;
$newSlug = str_replace(strrchr($slug , "-"), '',$slug);
$slug = $newSlug.'-'.$length;

$count++;

}else{
$slug = $slug.'-'.$counter;
}

}

$counter++;
$row = mysqli_fetch_assoc($result);

}while(mysqli_num_rows($result) > 0);

return $slug;

最佳答案

只需访问数据库一次,一次获取所有内容,这很可能是最大的瓶颈。

$query = "SELECT * FROM $table_name WHERE  $field_name  LIKE '".$slug."%'";

然后把你的结果放在一个数组中(比方说$slugs)

//we only bother doing this if there is a conflicting slug already
if(mysqli_num_rows($result) !== 0 && in_array($slug, $slugs)){
$max = 0;

//keep incrementing $max until a space is found
while(in_array( ($slug . '-' . ++$max ), $slugs) );

//update $slug with the appendage
$slug .= '-' . $max;
}

我们使用 in_array() 检查,就好像 slug 是 my-slug LIKE 也会返回这样的行

my-slug-is-awesome
my-slug-is-awesome-1
my-slug-rules

等等,这会导致问题,in_array() 检查确保我们只检查输入的确切 slug。

我们为什么不只计算结果并 +1?

这是因为如果您有多个结果并删除了一些,您的下一个 slug 很可能会发生冲突。

例如

my-slug
my-slug-2
my-slug-3
my-slug-4
my-slug-5

删除 -3 和 -5 留给我们

my-slug
my-slug-2
my-slug-4

所以,这给了我们 3 个结果,下一个插入将是 my-slug-4,它已经存在。

我们为什么不直接使用 ORDER BYLIMIT 1

我们不能只在查询中使用order by,因为缺少自然排序会使my-slug-10排名低于 my-slug-4,因为它逐个字符进行比较,4 高于 1

例如

m = m
y = y
- = -
s = s
l = l
u = u
g = g
- = -
4 > 1 !!!
< 0 (But the previous number was higher, so from here onwards is not compared)

关于php - 创建独特的页面标题 slugs php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15971685/

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