KenDev KenDev - 2 years ago 165
SQL Question

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

$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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download