Roland
Roland

Reputation: 9701

INSERT INTO ... ON DUPLICATE KEY UPDATE not working properly

I'm trying to run this query:

protected function store_credentials($config_file_path = 'envato_credentials_config.json') {
    $credentials_config = $this->get_envato_config($config_file_path);
    $sql = "INSERT INTO credentials (api_key, username, last_update) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE api_key = values(api_key), username = values(username), last_update = values(last_update)";
    if ($stmt = $this->connect->prepare($sql)) {
        $stmt->bind_param('ss', $credentials_config['API'], $credentials_config['User']);
        $stmt->execute();
        $stmt->close();
    } else {
        return false;
    }
}

But what happens is that I always get duplicate entries when it's executed, if it's executed again, instead of updating it runs again adding another two entries. Why is that happening ?

Upvotes: 0

Views: 2007

Answers (1)

barsju
barsju

Reputation: 4446

One of the columns you are inserting needs to be a primary key or have a unique constraint.

Upvotes: 6

Related Questions