How do I check for a duplicate record before inserting using wpdb

Let’s say the primary key of the table is my_part_ID. So we will check if there is any primary key value for the combination of user_ID and PL_part_ID as below

$my_part_ID = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT my_part_ID FROM " . $wpdb->prefix . "pl_my_parts
                    WHERE user_ID = %d AND PL_part_ID = %d LIMIT 1",
                    $user_ID, $PL_part_ID
                )
            );

if ( $my_part_ID > 0 )
    // exists
else
    // does not exist

Leave a Comment