gpt4 book ai didi

php - Joomla 将 mysql 表重新索引为函数

转载 作者:行者123 更新时间:2023-11-29 12:58:34 28 4
gpt4 key购买 nike

我正在尝试使用 php/joomla 中的函数重新索引表...它什么也不做。我也无法使用一个字符串创建整套 slq 命令。

function ReNumberID($TABLENAME ,$COLUMNNAME) {
$sql = "set @a=0; " ;
$db = JFactory::getDbo();

$query = $db->getQuery(true);

$db->setQuery($sql);
$db->execute();
$sql2 = "UPDATE `".$TABLENAME."` SET `".$COLUMNNAME."`=(@a:=@a+1); " ;

$db->setQuery($sql2);
$db->execute();
$sql3 = "SELECT * FROM `".$TABLENAME."` WHERE 1" ;

$db->setQuery($sql3);
$db->execute();
$newindexnumber = $db->getNumRows();
$newindexnumber++ ;
$sql4 = "ALTER TABLE `".$TABLENAME."` auto_increment = ".$newindexnumber." ;";

$db->setQuery($sql4);
$db->execute();
}

最佳答案

首先,我建议您检查每个查询,看看它们是否成功,以及有多少行受到影响。您当前正在调用 execute() 并相信确实发生了某些事情。谁知道您是否拼写错误列名或遇到权限错误或其他问题。

其次,您应该确保按照从当前低 ID 编号升序的顺序应用更新。因为你很容易导致错误。这是一个例子:

mysql> create table bar (id int primary key, x int) engine=myisam;
mysql> insert into bar (id) values (1), (5), (7), (2);
mysql> select * from bar;
+----+------+
| id | x |
+----+------+
| 1 | NULL |
| 5 | NULL |
| 7 | NULL |
| 2 | NULL |
+----+------+
mysql> set @a := 0;
mysql> update bar set id = (@a:=@a+1);
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'

原因是id 1设置为1,然后id 5设置为2,与第四行冲突。

mysql> update bar set id = (@a:=@a+1) order by id;
Query OK, 3 rows affected (0.00 sec)
mysql> select * from bar;
+----+------+
| id | x |
+----+------+
| 1 | NULL |
| 3 | NULL |
| 4 | NULL |
| 2 | NULL |
+----+------+

这至少有效。如果我没有检查错误,我永远不会知道重复键错误。

顺便说一句,您只需设置ALTER TABLE ... AUTO_INCRMENT=0,表格就会自动将其调整为 max(id)+1。

<小时/>

但这是我更强烈的建议:

不需要对自增键重新编号。主键必须是唯一的,但不要求是连续的。

有间隙是正常的。当 INSERT 失败,或者您删除一行,或者您 INSERT 但随后回滚时,就会发生这种情况。

如果对整个表中行的主键重新编号,可能会出现问题。例如,如果您的应用程序在数据库外部进行通信,则外部系统可能会通过旧 ID 记录实体。

示例:滥用用户 1234 骚扰其他用户,导致自己被禁止,他的帐户被关闭和删除。然后,您对所有 id 进行重新编号,并将 1234 分配给另一个新用户。第二天,一位律师出现并为您提供针对用户 1234 的民事投诉。这位可怜的新用户因其他人所做的事情而受到指责。

我在我的书中写到了这一点,SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming 。关于这个错误的章节称为“Pseudokey Neat-Freak”。

关于php - Joomla 将 mysql 表重新索引为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667551/

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