How to avoid duplicates in INSERT INTO wordpress

I am trying to insert record into wordpress tables but the problem is, its inserting duplicate records.

This is my sql query

Read More
$qv = $conn->query("INSERT INTO wp_posts (post_title, post_content, post_name, post_date, post_date_gmt, post_author) VALUES('$title[$i]', '$description[$i]', '$url[$i]', '$date[$i]', '$postdate[$i]', '$author[$i]') ON DUPLICATE KEY UPDATE post_name = post_name");

I don’t want to insert any duplicate records, how to fix this?

Related posts

3 comments

  1. create unique key on column and use insert ignore instead of insert like below

      ("INSERT ignore INTO wp_posts (post_title, post_content, post_name, post_date, post_date_gmt, post_author)
     VALUES('$title[$i]', '$description[$i]', '$url[$i]', '$date[$i]', '$postdate[$i]', '$author[$i]'));
    
  2. wp_posts has id as auto increment primary key and your insert query does not have id, hence your on duplicate constraint will not work.
    If you want to have unique record by post title then you will have to create unique index on it. Unique constraint can be applied to combination of more than one column, if necessary.
    Also insert ignore will igonre the duplicate records and not update it. You will have to handle it in your application.

    Query to add Unique Constraint in MySQL

    ALTER TABLE wp_posts ADD CONSTRAINT unique_post UNIQUE (post_title,post_name);
    
  3. Disallow Duplicate Post Using Titles

    function disallow_posts_with_same_title($messages) {
        global $post;
        global $wpdb ;
        $title = $post->post_title;
        $post_id = $post->ID ;
        $wtitlequery = "SELECT post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND post_title = '{$title}' AND ID != {$post_id} " ;
    
        $wresults = $wpdb->get_results( $wtitlequery) ;
    
        if ( $wresults ) {
            $error_message = 'This title is already used. Please choose another';
            add_settings_error('post_has_links', '', $error_message, 'error');
            settings_errors( 'post_has_links' );
            $post->post_status = 'draft';
            wp_update_post($post);
            return;
        }
        return $messages;
    
    }
    add_action('post_updated_messages', 'disallow_posts_with_same_title');
    

Comments are closed.