Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL INSERT IGNORE / ON DUPLICATE KEY UPDATE not detecting duplicates
    primarykey
    data
    text
    <p>I'm having an issue here, and after 2 hours of Googling Stackoverflow answers and testing different ideas I can't figure it out. Hopefully it's a no-brainer for someone out there.</p> <p><strong>EDIT: Fixed! See solutions below.</strong></p> <p><em>Here is my code:</em></p> <pre><code>// Establish Table and vars mysql_query("CREATE TABLE IF NOT EXISTS pages(page varchar(255), content varchar(255))"); $page = 'Hello'; $content = 'This is the content.'; // Ive tried this: mysql_query("INSERT INTO pages SET page='$page' ON DUPLICATE KEY UPDATE content='$content'"); // Ive also tried: mysql_query("INSERT IGNORE INTO pages SET page='$page', content='$content'")); mysql_query("INSERT IGNORE INTO pages SET page='$page'")); // No content </code></pre> <p><em>Expected result:</em> Create one row with 'page' value of 'Hello' ('content' value of 'This is the content.'). When script is run a second time, no additional row is created, because there is already a row with 'page' value of 'Hello'.</p> <p><em>Observed Result:</em> Every time script is run, a new row with page value of 'Hello' is created, assumedly because this is not a duplicate key. Buy why not? I have tried creating a table with an ID field that is AUTO_INCREMENT and the primary key, but I thought that was causing the problem so I simplified it. </p> <p><em>(That code was:)</em></p> <pre><code>mysql_query("CREATE TABLE IF NOT EXISTS pages(id INT AUTO_INCREMENT NOT NULL, page varchar(255), content varchar(255), primary key (id))"); </code></pre> <p><em>Desired Result:</em> A new row should be inserted into the table if there is no row with a 'page' field of 'Hello.' Once this has been created, running the same script again should NOT result in a new row.</p> <p>Thank you!</p> <p><strong>EDIT: Fixed! See solutions below.</strong></p> <p>My solution:</p> <pre><code>// Table needs a primary key to search for duplicates. mysql_query("CREATE TABLE IF NOT EXISTS pages(page varchar(255), content varchar(255), primary key (page))"); // Establish Table </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload