我正在编写一个插件,并尝试在 foreach 循环内的 wp_term_relationships 表中插入一个新行。我知道变量由于 var_dump 而具有值,但由于某种原因,我始终收到错误。这在 show_errors() 函数中出现了大约 600 次:
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
的第三个参数设置为空字符串。它相应地格式化每个字段..
它现在所做的相当于:
$wpdb->insert($table, array(
'object_id' => sprintf('', $num_object_id),
'term_taxonomy_id' => sprintf('', $num_taxo_id),
'term_order' => sprintf('', 0)
));
如果你确实想设置第三个参数,你应该这样做:
$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。
虽然发生这种情况是因为通过将 insert 的第三个参数设置为空字符串,您试图一遍又一遍地插入 object_id=0 和 term_taxonomy_id=0 的行。
关于php - $wpdb->插入产生 "Duplicate entry ' 0- 0' for Key ' 1' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9429958/