Handling duplicate keys in wordpress database

I’m want to write a function that saves a user data array to a custom table in my wp database. I have this working with this function.

function insert_player($playerArray){
    global $wpdb;
    $table_name = $wpdb->prefix . "hots_logs_plugin";
    $wpdb->insert(
        $table_name,
        array(
            'name' => $playerArray['name'], 
            'player_id' => $playerArray['pid'], 
            'hl_mmr' => $playerArray['heroLeague'], 
            'qm_mmr' => $playerArray['quickMatch'],
            'comb_hero_level' => $playerArray['combLevel'], 
            'total_games_played' => $playerArray['totalGames']
        )
    );  
}

Now I want to extend this function so that if a duplicate player_id is sent the function updates the all the cells in the row apart from the name and player_id. The player_id is a UNIQUE KEY.

Read More

I have come up with this function, which I can’t seem to get to work, and to be honest is a little over my head..

function input($playerArray){
    global $wpdb;
    $table_name = $wpdb->prefix . "hots_logs_plugin";

    $sql = "INSERT INTO $table_name(player_id, name, hl_mmr, qm_mmr, comb_hero_level, total_games_played) 
            VALUES(%d,%s,%s,%s,%s,%s) 
            ON DUPLICATE KEY UPDATE(hl_mmr = %s, qm_mmr = %s, comb_hero_level = %s, total_games_played = %s)";

    $sql = $wpdb->prepare(
        $playerArray['pid'],
        $playerArray['name'],
        $playerArray['heroLeague'],
        $playerArray['quickMatch'],
        $playerArray['combLevel'],
        $playerArray['totalGames']
        );

    $wpdb->query($sql);
}    

I just need a nudge in the right direction.

Related posts

1 comment

  1. OK, so I was really over doing it in my first attempt. The answer is actually really easy.

    I just modified the original method to use $wpdb->replace() rather than $wpdb->insert()

    The following method works great.

    function insert_player($playerArray){
        global $wpdb;
        $table_name = $wpdb->prefix . "hots_logs_plugin";
        $wpdb->replace(
            $table_name,
            array(
                'player_id' => $playerArray['pid'], 
                'name' => $playerArray['name'], 
                'hl_mmr' => $playerArray['heroLeague'], 
                'qm_mmr' => $playerArray['quickMatch'],
                'comb_hero_level' => $playerArray['combLevel'], 
                'total_games_played' => $playerArray['totalGames']
            ),
            array (
                '%d',
                '%s',
                '%s',
                '%s',
                '%s',
                '%s'
            )
        );  
    }
    

Comments are closed.