只需访问数据库一次,立即获取所有内容,很可能这是最大的瓶颈。
$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()
检查是否是蛞蝓my-slug
the LIKE
还会返回诸如
my-slug-is-awesome
my-slug-is-awesome-1
my-slug-rules
等会引起问题的in_array()
检查确保我们只检查输入的确切段。
为什么我们不直接计算结果并+1?
这是因为,如果您有多个结果,并删除了一些结果,那么您的下一个 slug 很可能会发生冲突。
E.g.
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 BY
and LIMIT 1
?
We can't just do an order by
in the query because the lack of natural sorting would make my-slug-10
rank lower than my-slug-4
as it compares character by character and 4
is higher than 1
E.g.
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)