$wpdb->insert is not respacting unique fields

I have been creating WordPress plugin for a while. This is example of mysql table:

$sql = "CREATE TABLE IF NOT EXISTS $table_name  (
    id INT(11) NOT NULL AUTO_INCREMENT,
    email       VARCHAR(100) DEFAULT NULL,
    telephone   VARCHAR(15) DEFAULT NULL,
    PRIMARY KEY(id),
    UNIQUE (email, telephone)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
";

Email should be unique, right? phpMyAdmin says it it.

Read More

This is wordpress code that inserts data into that table:

$err = $wpdb->insert($wpdb->prefix.$table_name, $data, $format);
var_dump($err);

It works, even more than it should. Assume email is m@m.com. First insert goes well. Second try fails because of duplicate entry as it should. var_dump is false.
BUT if I refresh wp page, third try with same email passes flawlessly, var_dump 1. Any repeated wp refresh opens db for duplicate entry.
Why? What am I doing wrong?

Related posts

Leave a Reply

1 comment

  1. No, email is not UNIQUE here. Pair of email and telephone is UNIQUE in your table definition.

    $sql = "CREATE TABLE IF NOT EXISTS $table_name  (
        id INT(11) NOT NULL AUTO_INCREMENT,
        email       VARCHAR(100) DEFAULT NULL,
        telephone   VARCHAR(15) DEFAULT NULL,
        PRIMARY KEY(id),
        UNIQUE (email),
        UNIQUE (telephone)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='WP plugin sesa_players db' AUTO_INCREMENT=1 ;
    ";
    

    Probably this is what you want.