php - $wpdb->插入产生 "Duplicate entry ' 0- 0' for Key ' 1' "

标签 php mysql wordpress insert-into

我正在编写一个插件,并尝试在 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/

相关文章:

php - session_destroy() 根本不起作用

php - Symfony2 命令 "doctrine:schema:update"未检测实体中使用的特征文件更改

php - 回显重复列值的详细信息

mysql - 使得两个sql字段在改变之前需要互相更新

WordPress 元查询不起作用

java - 在java中创建可以在php api中反序列化的字符串的有效方法

php - 如何基于 GET 搜索选择多个字段?

mysql - 无法从 Node js插入mysql

wordpress - 无法登录 WordPress 网站...Azure 上的自托管

wordpress - 完整的 Magento/Wordpress 集成