Checking for Unique Key and updating row or creating a new one WordPress

I have a draggable div in which the position is being saved to database with user_id set to unique. How would I check if user_id exists.. and if it does, update the other 3 columns.. If it does not exist, insert new row. I have read to use “ON DUPLICATE KEY UPDATE”, but having a hard time implementing it. Any thoughts?

Code has been edited to reflect @true ‘s suggestion.. Works perfectly!

global $wpdb;

    $_POST['user_id'];
    $_POST['div_id'];
    $_POST['x_pos'];
    $_POST['y_pos'];

    $user_id    = $_POST['user_id'];
    $div_id     = $_POST['div_id'];
    $x_pos      = $_POST['x_pos'];
    $y_pos      = $_POST['y_pos'];

$user_exists = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM coords WHERE user_id = %d", $user_id));
    if($user_exists) {

    $wpdb->update('coords', array(

        'div_id'        => $div_id, 
        'x_pos'         => $x_pos, 
        'y_pos'         => $y_pos),

        array(
        'user_id'   => $user_id)); 

    } else {

    $wpdb->insert('coords', array (

        'user_id'       => $user_id, 
        'div_id'        => $div_id, 
        'x_pos'         => $x_pos, 
        'y_pos'         => $y_pos

    )); 
    }   


Source: wpdb

Leave a Reply