$wpdb->insert 产生 "密钥“1"的重复条目“0-0" [英] $wpdb->insert produces " Duplicate entry '0-0' for Key '1' "
问题描述
我正在编写一个插件并尝试在 foreach 循环内的 wp_term_relationships 表中插入一个新行.由于 var_dump,我知道变量具有值,但由于某种原因,我始终收到错误消息.这在 show_errors() 函数中出现了大约 600 次:
I'm writing a plugin and trying to insert a new row into the wp_term_relationships table inside of a foreach loop. I know the variables have values because of a var_dump, but for some reason, I'm getting an error consistently. This shows up about 600 times on the show_errors() function:
WordPress 数据库错误:[重复条目 '0-0' for key 1] INSERTINTO wp_term_relationships
(object_id
,term_taxonomy_id
,term_order
) VALUES ('','','')
WordPress database error: [Duplicate entry '0-0' for key 1] INSERT INTO
wp_term_relationships
(object_id
,term_taxonomy_id
,term_order
) VALUES ('','','')
我的代码:
foreach ($cb_t2c_cat_check as $values) {
global $wpdb;
$prefix = $wpdb->prefix;
$table = $prefix . 'term_relationships';
$object_id = $values->object_id;
$taxo_id = $values->term_taxonomy_id;
$num_object_id = (int)$object_id;
$num_taxo_id = (int)$taxo_id;
//var_dump($num_object_id); //This produces values, so why are they not getting inserted into the table?
//var_dump($num_taxo_id); //This produces values, so why are they not getting inserted into the table?
$wpdb->insert(
$table,
array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), ''
);
//$wpdb->show_errors();
//$wpdb->print_error();
}
推荐答案
至于为什么不起作用:不要将 $wpdb->insert
的第三个参数设置为空字符串.它相应地格式化每个字段..
As for why it does not work: do not set third parameter of $wpdb->insert
to empty string. It formats every field accordingly..
它现在的作用相当于:
$wpdb->insert($table, array(
'object_id' => sprintf('', $num_object_id),
'term_taxonomy_id' => sprintf('', $num_taxo_id),
'term_order' => sprintf('', 0)
));
如果你真的想设置第三个参数,你应该这样做:
If you really want to set third parameter you should do:
$wpdb->insert($table, array(
'object_id' => $num_object_id,
'term_taxonomy_id' => $num_taxo_id,
'term_order' => 0
), array('%d', '%d', '%d'));
<小时>
至于错误:wp_term_relationships 表在 (object_id, term_taxonomy_id) 上有一个唯一的主键.这意味着该表中不能有两行同时具有相同的 object_id 和 term_taxonomy_id.
As for error: wp_term_relationships table has a unique primary key on (object_id, term_taxonomy_id). This means that you cannot have two rows in that table which have both same object_id and term_taxonomy_id.
虽然发生这种情况是因为通过将 insert 的第三个参数设置为空字符串,您试图一遍又一遍地插入 object_id=0 和 term_taxonomy_id=0 的行.
Though this has happened because by setting third parameter of insert to empty string, you are trying to insert rows with object_id=0 and term_taxonomy_id=0 over and over again.
这篇关于$wpdb->insert 产生 "密钥“1"的重复条目“0-0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!