I am inserting a row into a custom table in a wordpress database. this is the code:

$wpdb->insert( 'wp_pl_my_parts', 
                    array( 
                    'user_ID' => $user_ID, 
                    'PL_part_ID' => $PL_part_ID, 
                    'part_save_date' => $part_save_date ), array( '%d', '%d', '%s' ) );

How do I make sure I do not insert a duplicate entry. Ie. I don’t want it to insert if the user_ID and the PL_part_ID are the same as an existing record?

Date doesn’t matter and shouldn’t be checked.

4 s
4

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 Reply

Your email address will not be published. Required fields are marked *